14

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)
Paul
  • 519
  • 1
  • 4
  • 6
  • There is a similar questions asked here: http://stackoverflow.com/questions/6878418/putting-a-cookie-in-a-cookiejar – robert king Jun 20 '13 at 23:58

1 Answers1

37

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/>
Blender
  • 257,973
  • 46
  • 399
  • 459
Paul
  • 519
  • 1
  • 4
  • 6