Reputation: 4028
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
Upvotes: 6
Views: 13807
Reputation: 1618
You can add cookies the better way using the set_simple_cookie
function.
Considering your cookies are in json,
{
"domain": ".example.com",
"expirationDate": 1651137273.706626,
"hostOnly": false,
"httpOnly": true,
"name": "SecureExampleId",
"path": "/",
"sameSite": "strict",
"secure": true,
"session": false,
"storeId": null,
"value": "v%3D2%26mac%..."
}
import http.cookiejar
cookiejar = http.cookiejar.LWPCookieJar()
br.set_cookiejar(cookiejar)
br.set_simple_cookie(cookie['name'], cookie['value'], cookie['domain'], cookie['path'])
response = br.open(url)
print(cookiejar._cookies)
Upvotes: 0
Reputation: 64
To set a cookie with python mechanize, first grab websites cookies and save them to file "cookies.lwp":
import mechanize, cookielib
cj = cookielib.LWPCookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.open('https://www.somesite.com')
cj.save(filename="cookies.lwp", ignore_discard=False, ignore_expires=False)
You can now set any cookie in "cookies.lwp" to whatever value you want and then load them back into your browser:
cj.load(filename="modified_cookies.lwp", ignore_discard=False, ignore_expires=False)
br.set_cookiejar(cj)
br.open('https://www.yoursitehere.com')
for cookie in cj:
print cookie
This video will walk you through it How To Modify Cookies with Python Mechanize
Upvotes: 1
Reputation: 510
you can also add a preexisting cookie manually with the addheaders method from mechanize's browser class.
br.addheaders = [('Cookie','cookiename=cookie value')]
Upvotes: 5
Reputation: 2242
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)
Upvotes: 6
Reputation: 879103
import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.CookieJar()
br.set_cookiejar(cj)
Upvotes: 1