简体   繁体   English

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

[英]How do I clear the cookies in urllib.request (python3)

Looking through the docs my first guess was that I call urllib.request.HTTPCookieProcessor().cookiejar.clear(), however that didn't work. 通过文档查看我的第一个猜测是我调用urllib.request.HTTPCookieProcessor()。cookiejar.clear(),但是这不起作用。 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. 我不知道该怎么做,如果需要的话我当然可以,但是我认为这应该是一个简单的操作似乎有些过分。

By default, urllib.request won't store any cookies, so there is nothing to clear. 默认情况下, urllib.request不会存储任何cookie,因此无需清除。 If you build an OpenerDirector containing and HTTPCookieProcessor instance as one of the handlers, you have to clear the cookiejar of this instance. 如果你建立一个OpenerDirector含和HTTPCookieProcessor实例作为处理程序之一,你必须清除cookiejar此实例。 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() . 如果要清除cj的cookie,只需调用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. 您尝试过的调用urllib.request.HTTPCookieProcessor().cookiejar.clear()将创建一个新的HTTPCookieProcessor实例,该实例将有一个空的cookiejar ,清除cookiejar (无论如何都是空的)并再次删除整个内容,因为你不cookiejar t存储对任何创建对象的引用 - 简而言之,它什么都不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM