如何清除 urllib.request 中的 cookie (python3)
查看文档,我的第一个猜测是我调用了 urllib.request.HTTPCookieProcessor().cookiejar.clear(),但这不起作用。我的下一个猜测是,也许我需要对其进行子类化并使用开启器构建/安装它?我不知道该怎么做,当然,如果需要的话我可以,但对于我认为应该如此简单的操作来说,这似乎有点矫枉过正。
Looking through the docs my first guess was that I call urllib.request.HTTPCookieProcessor().cookiejar.clear(), however that didn't work. My next guess is maybe I need to subclass it and build/install it with an opener? I don't know how to do that, I can if need be of course, but it really seems like overkill for what I feel should be such a simple operation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,
urllib.request
不会存储任何cookie,因此无需清除任何内容。如果您构建一个包含OpenerDirector
和HTTPCookieProcessor
实例作为处理程序之一,则必须清除该实例的cookiejar
。 文档中的示例:如果您想清除
cj
,只需调用cj.clear()
。您尝试的调用
urllib.request.HTTPCookieProcessor().cookiejar.clear()
将创建一个新的HTTPCookieProcessor
实例,该实例将有一个空的cookiejar
,清除 cookiejar(无论如何都是空的)并再次删除整个内容,因为您不存储对任何创建的对象的引用 - 简而言之,它不会执行任何操作。By default,
urllib.request
won't store any cookies, so there is nothing to clear. If you build anOpenerDirector
containing andHTTPCookieProcessor
instance as one of the handlers, you have to clear thecookiejar
of this instance. Example from the docs:If you want to clear the cookies in
cj
, just callcj.clear()
.The call
urllib.request.HTTPCookieProcessor().cookiejar.clear()
you tried will create a newHTTPCookieProcessor
instance which will have an emptycookiejar
, clear thecookiejar
(which is empty anyway) and drop the whole thing again, since you don't store references to any of the created objects -- so in short, it will do nothing.