http://stackoverflow.com/questions/14742899/using-cookies-txt-file-with-python-requests
Using cookies.txt file with Python Requests
I'm trying to access an authenticated site using a
cookies.txt
file (generated with a Chrome extension) with Python Requests:import requests, cookielib
cj = cookielib.MozillaCookieJar('cookies.txt')
cj.load()
r = requests.get(url, cookies=cj)
It doesn't throw any error or exception, but yields the login screen, incorrectly. However, I know that my cookie file is valid, because I can successfully retrieve my content using it with
wget
. Any idea what I'm doing wrong?
Edit:
I'm tracing
cookielib.MozillaCookieJar._really_load
and can verify that the cookies are correctly parsed (i.e. they have the correct values for the domain
, path
, secure
, etc. tokens). But as the transaction is still resulting in the login form, it seems that wget
must be doing something additional (as the exact same cookies.txt
file works for it).MozillaCookieJar
inherits from FileCookieJar
which has the following docstring in its constructor:Cookies are NOT loaded from the named file until either the .load() or
.revert() method is called.
You need to call
.load()
method then.
Also, like Jermaine Xu noted the first line of the file needs to contain either
# Netscape HTTP Cookie File
or # HTTP Cookie File
string. Files generated by the plugin you use do not contain such a string so you have to insert it yourself. I raised appropriate bug at http://code.google.com/p/cookie-txt-export/issues/detail?id=5
EDIT
Session cookies are saved with 0 in the 5th column. If you don't pass
ignore_expires=True
to load()
method all such cookies are discarded when loading from a file.
File
session_cookie.txt
:# Netscape HTTP Cookie File
.domain.com TRUE / FALSE 0 name value
Python script:
import cookielib
cj = cookielib.MozillaCookieJar('session_cookie.txt')
cj.load()
print len(cj)
Output:
0
NEXT PROBLEM GUYS..ACCESSING MANAGEMENT CODE...
No comments:
Post a Comment