How do I add a cookie to a urllib2 opener?

1.4k Views Asked by At

I have created an opener with urllib2.build_opener() that contains a cookielib.CookieJar(), and now I wish to manually add a cookie to the opener.

How can I achieve this?

1

There are 1 best solutions below

2
On

Like the second example of the cookielib documentation suggests:

import os, cookielib, urllib2
cj = cookielib.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

Here's the link:

Cookies examples

Above example applies to Mozilla cookies, but generic algorithm is the same.

If adding by hand is required, reading the documentation further, you can use:

http://docs.python.org/library/cookie.html#module-Cookie Cookie object, which you fill up the way you see fit and further on add it to a CookieJar with

CookieJar.set_cookie(cookie)

Set a Cookie, without checking with policy to see whether or not it should be set.