How do I clear the cookies in urllib.request (python3)
Asked Answered
R

1

7

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.

Refresh answered 15/2, 2011 at 23:53 Comment(0)
P
17

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.

Prestissimo answered 16/2, 2011 at 0:20 Comment(1)
Perfect. Turns out my problem was in parsing the html, not reading it, so I fixed it, but still I'll need to know this for the future.Refresh

© 2022 - 2024 — McMap. All rights reserved.