1

When I get the Set-Cookie and try to use it, I wont seem that I'm logged in Facebook...

import urllib, urllib2

data = urllib.urlencode({"email":"swagexample@hotmail.com", "pass":"password"})
request = urllib2.Request("http://www.facebook.com/login.php", data)
request.add_header("User-Agent", "Mozilla 5.0")

response = urllib2.urlopen(request)
cookie = response.headers.get("Set-Cookie")
new_request = urllib2.Request("http://www.facebook.com/login.php")
new_request.add_header("User-Agent", "Mozilla 5.0")
new_request.add_header("Cookie", cookie)

new_response = urllib2.urlopen(new_request)
if "Logout" in new_response.read():
        print("Logged in.") #No output

Why?

falsetru
  • 357,413
  • 63
  • 732
  • 636
user3818650
  • 581
  • 1
  • 7
  • 19

1 Answers1

1

First, Set-Cookie header format is different from Cookie header.

Set-Cookie header contains additional information (doamin, expire, ...), you need to convert them to use it for Cookie header.

cookie = '; '.join(
    x.split(';', 1)[0] for x in response.headers.getheaders("Set-Cookie")
)

Even though you do above, you will still not get what you want, because default urllib2 handler does not handle cookie for redirect.

Why don't you use urllib2.HTTPCookieProcessor as you did before?

Community
  • 1
  • 1
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • I already know how to use that, its just I need to learn how to do this properly also. – user3818650 Oct 05 '14 at 15:16
  • 1
    @user3818650, If you really want to do it without HTTPCookieProcessor, disable automatic redirect. Then handle redirect yourself (with proper cookie set). – falsetru Oct 05 '14 at 15:17
  • 1
    @user3818650, FYI, [How do I prevent Python's urllib(2) from following a redirect](http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect) – falsetru Oct 05 '14 at 15:17