How to clear cookies in urllib.request (python3)

Looking through the docs, I first assumed that I was calling urllib.request.HTTPCookieProcessor (). cookiejar.clear () however this did not work. My next suggestion, maybe I need to subclass it and build / install it using an opener? I don’t know how to do this, I can, if necessary, of course, but it really seems unnecessary, because I feel that it is such a simple operation.

+7
source share
1 answer

By default, urllib.request will not store cookies, so there is nothing to clear. If you create an instance of OpenerDirector and an HTTPCookieProcessor as one of the handlers, you must clear the cookiejar that instance. Example from the documentation :

 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 cookies in cj just call cj.clear() .

If you try to call urllib.request.HTTPCookieProcessor().cookiejar.clear() , a new instance of HTTPCookieProcessor will be created that will have an empty cookiejar , clear the cookiejar (which is still empty) and all this will be cookiejar again, since you will not store links to any from the created objects - so, in short, he will not do anything.

+17
source

All Articles