Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 717
kryptobs2000 Avatar asked Feb 15 '11 23:02

kryptobs2000


People also ask

How to retrieve cookies from a URL in Python?

Retrieving cookies in Python can be done by the use of the Requests library. Requests library is one of the integral part of Python for making HTTP requests to a specified URL. The below codes show different approaches to do show: 1. By requesting a session:

How to delete a browser cookie in Python?

Deleting a browser cookie using Python is as simple as setting the cookie. However, when we want to delete a cookie, we just need to set it to an empty value. Here is how we do it:

What is urllib request Python?

Source code: Lib/urllib/request.py The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. The Requests package is recommended for a higher-level HTTP client interface.

How do I set a cookie in Python?

Setting HTML Browser Cookies in Python. In order to set HTML browser cookies in a client's browser using python, you just need these two lines of code: The above code snippet will create a cookie named UserID in the browser and then set it's value to 12345. After this the user will be redirected to a new page.


1 Answers

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.

like image 94
Sven Marnach Avatar answered Sep 21 '22 23:09

Sven Marnach