如何清除 urllib.request 中的 cookie (python3)

发布于 2024-10-18 03:10:59 字数 171 浏览 5 评论 0原文

查看文档,我的第一个猜测是我调用了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗藏城府 2024-10-25 03:10:59

默认情况下,urllib.request不会存储任何cookie,因此无需清除任何内容。如果您构建一个包含 OpenerDirectorHTTPCookieProcessor 实例作为处理程序之一,则必须清除该实例的 cookiejar文档中的示例

import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

如果您想清除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 an OpenerDirector containing and HTTPCookieProcessor instance as one of the handlers, you have to clear the cookiejar of this instance. Example from the docs:

import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

If you want to clear the cookies in cj, just call cj.clear().

The call urllib.request.HTTPCookieProcessor().cookiejar.clear() you tried will create a new HTTPCookieProcessor instance which will have an empty cookiejar, clear the cookiejar (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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文