kryptobs2000
kryptobs2000

Reputation: 3537

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. 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.

Upvotes: 7

Views: 9668

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602145

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.

Upvotes: 17

Related Questions