Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set cookie in python mechanize

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

like image 954
John Avatar asked Mar 17 '13 09:03

John


2 Answers

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)
like image 99
C R Avatar answered Nov 10 '22 07:11

C R


you can also add a preexisting cookie manually with the addheaders method from mechanize's browser class.

br.addheaders = [('Cookie','cookiename=cookie value')]
like image 25
neif Avatar answered Nov 10 '22 07:11

neif