How to enter the site using the python module "mechanize" with the cookies.txt file exported by the chrome extension "export.txt export"?

I looked at similar questions in stackoverflow, but there seemed to be no answers. Now I have a cookie.txt in my hands that is exported by the chrome extension named "cookie.txt". I can run the command "wget ​​--load-cookies cookie.txt www.example.com" to load the account authentication web page.

However, I ran into a problem when I tried to use this file in my python script as follows,

import mechanize cookie = 'cookies.txt' cookiejar = mechanize.FileCookieJar(cookies.txt) br = mechanize.Browser() br.set_handle_robots(False) br.set_cookiejar(cookiejar) url = 'www.example.com' response = br.open(url) s = response.read() f = open('test.html','w') f.write(s) f.close() 

I only got a webpage without registering my account after running this script. And if I changed the first few lines of code to this

 import mechanize cookie = 'cookies.txt' cookiejar = mechanize.MozillaCookieJar() cookiejar.load(cookie) 

I got the error message "mechanize._clientcookie.LoadError: cookies.txt do not look like Netscape format cookies" executing a script.

I have no idea how I can authenticate with this cookie.txt, given that this file works in the wget command.

+4
source share
3 answers

I was getting the same error until I added it to the top of my cookie and now it works.

 # Netscape HTTP Cookie File # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. 
+2
source

According to the mechanization source code, the MozillaCookieJar class loading method will first search for the regular expression "# (Netscape)" HTTP Cookie File ", so you can paste this line at the top of the exported cookie.txt:

 # Netscape HTTP Cookie File 
+2
source

Use the cookielib module to process cookies.

http://docs.python.org/library/cookielib.html

In particular, you need to read how to use FileCookieJar.load ()

That should let you down.

0
source

All Articles