When I would try to get the set cookie of an response instance I would get an None value when I use my actual login username and password.
import urllib2, urllib, cookielib
jar = cookielib.CookieJar()
cookie = urllib2.HTTPCookieProcessor(jar)
opener = urllib2.build_opener(cookie)
data = urllib.urlencode({'email':'user@hotmail.com','pass':'password','login':'Log+In'})
req = urllib2.Request('http://www.facebook.com/login.php')
response = opener.open(req, data)
response = opener.open(req, data) #I open it twice on purpose
if "Logout" in response.read():
print("Logged In")
else:
print("Not Logged In")
cookie_header = response.headers.get("Set-Cookie")
print(cookie_header)
I know how to set the cookie header, but the problem is a None value is being assigned to cookie_header when I use my actual credentials. How do I get the cookie?
By rearranging the code I was able to fix it up.
response = opener.open(req, data)
cookie_header = response.headers.get("Set-Cookie")
response = opener.open(req, data) #I open it twice on purpose
Because the cookie was set on the first open.
The cookie will be set on the first response, you are testing the second instead. Facebook won't set another cookie here.
You could just get the cookie from the CookieJar
object:
cookie = list(cookie.cookiejar)[0]
You'd have a much easier time of it if you used the request
library instead:
import requests
session = requests.Session()
data = {'email':'user@hotmail.com','pass':'password','login':'Log+In'}
form = session.get('http://www.facebook.com/login.php')
response = session.post('http://www.facebook.com/login.php', data/data)
cookie_value = session.cookie['datr']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.