how to set cookie in python mechanize

2020-06-20 04:59发布

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

3条回答
ら.Afraid
2楼-- · 2020-06-20 05:26

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)
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-06-20 05:27

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

br.addheaders = [('Cookie','cookiename=cookie value')]
查看更多
混吃等死
4楼-- · 2020-06-20 05:43
import mechanize
import cookielib

br = mechanize.Browser()
cj = cookielib.CookieJar()
br.set_cookiejar(cj)
查看更多
登录 后发表回答