how to set cookie in python mechanize

John picture John · Mar 17, 2013 · Viewed 12.2k times · Source

After sending request to the server

    br.open('http://xxxx')
    br.select_form(nr=0)   
    br.form['MESSAGE'] = '1 2 3 4 5'
    br.submit()

I get the response title, which has set-cookie

Set-Cookie: PON=xxx.xxx.xxx.111; expires=Tue, 17-Mar-2015 00:00:00 GMT; path=/

Because mechanize seems to be not able to remember the cookie, so I want to set cookie for br. How can I do it?

    cj = mechanize....?
    br.set_cookiejar(cj)

I have no idea. Please help

Answer

C R picture C R · Dec 8, 2013

I think that this should do what you want:

import Cookie
import cookielib
cookiejar =cookielib.LWPCookieJar()

br = mechanize.Browser()
br.set_cookiejar(cookiejar)
cookie = cookielib.Cookie(version=0, name='PON', value="xxx.xxx.xxx.111", expires=365, port=None, port_specified=False, domain='xxxx', domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=True, discard=False, comment=None, comment_url=None, rest={'HttpOnly': False}, rfc2109=False)
cookiejar.set_cookie(cookie)