how to set cookie in python mechanize

不想你离开。 提交于 2019-12-21 05:00:27

问题


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


回答1:


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)



回答2:


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

br.addheaders = [('Cookie','cookiename=cookie value')]



回答3:


import mechanize
import cookielib

br = mechanize.Browser()
cj = cookielib.CookieJar()
br.set_cookiejar(cj)


来源:https://stackoverflow.com/questions/15459217/how-to-set-cookie-in-python-mechanize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!