Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add cookie to existing cookielib CookieJar instance in Python?

I have a CookieJar that's being used with mechanize that I want to add a cookie to. How can I go about doing this? make_cookie() and set_cookie() weren't clear enough for me.

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
like image 556
Paul Avatar asked Jan 30 '10 20:01

Paul


People also ask

How do you add cookies in Python?

#!/usr/bin/python print "Set-Cookie:UserID = XYZ;\r\n" print "Set-Cookie:Password = XYZ123;\r\n" print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n" print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n" print "Set-Cookie:Path = /perl;\n" print "Content-type:text/html\r\n\r\n" ...........

What is cookie jar in Python?

cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.

How do you use a cookie jar?

If, however, you are using an older model cookie jar, the answer is quite simple. Just put the cookies in a zip-style plastic bag, seal it up, and put the bag in the jar. Whenever you reach in for a cookie, it's an easy step to open the bag and close it back up to keep those cookies fresh.


1 Answers

Managed to figure this out

import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
ck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
cj.set_cookie(ck)
for index, cookie in enumerate(cj):
    print index, ' : ', cookie

Output:

0  :  <Cookie Name=1 for www.example.com/>
like image 171
Paul Avatar answered Sep 20 '22 13:09

Paul