views:

270

answers:

2

I've found a PHP script that lets me do what I asked in this SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python.

I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python?

require_once "HTTP/Request.php";

$req = &new HTTP_Request('https://steamcommunity.com');
$req->setMethod(HTTP_REQUEST_METHOD_POST);

$req->addPostData("action", "doLogin");
$req->addPostData("goto", "");

$req->addPostData("steamAccountName", ACC_NAME);
$req->addPostData("steamPassword", ACC_PASS);

echo "Login: ";

$res = $req->sendRequest();
if (PEAR::isError($res))
  die($res->getMessage());

$cookies = $req->getResponseCookies();
if ( !$cookies )
  die("fail\n");

echo "pass\n";

foreach($cookies as $cookie)
  $req->addCookie($cookie['name'],$cookie['value']);
+5  A: 

I'm not familiar with PHP, but this may get you started. I'm installing the opener here which will apply it to the urlopen method. If you don't want to 'install' the opener(s) you can use the opener object directly. (opener.open(url, data)).

Refer to: http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener

import urlib2
import urllib

# 1 create handlers
cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling
redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection

# 2 apply the handler to an opener                                                  
opener = urllib2.build_opener(cookieHandler, redirectionHandler)

# 3. Install the openers
urllib2.install_opener(opener)

# prep post data
datalist_tuples = [ ('action', 'doLogin'),
                    ('goto', ''),
                    ('steamAccountName', ACC_NAME),
                    ('steamPassword', ACC_PASS)

                   ]
url = 'https://steamcommunity.com'
post_data = urllib.urlencode(datalist_tuples)
resp_f = urllib2.urlopen(url, post_data)
monkut
+1 to both your and MizardX's answers... they'd be perfect combined :-)
Jarret Hardie
+6  A: 

Similar to monkut's answer, but a little more concise.

import urllib, urllib2

def steam_login(username,password):
    data = urllib.urlencode({
      'action': 'doLogin',
      'goto': '',
      'steamAccountName': username,
      'steamPassword': password,
    })
    request = urllib2.Request('https://steamcommunity.com/',data)
    cookie_handler = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookie_handler)
    response = opener.open(request)
    if not 200 <= response.code < 300:
        raise Exception("HTTP error: %d %s" % (response.code,response.msg))
    else:
        return cookie_handler.cookiejar

It returns the cookie jar, which you can use in other requests. Just pass it to the HTTPCookieProcessor constructor.

monkut's answer installs a global HTTPCookieProcessor, which stores the cookies between requests. My solution does not modify the global state.

MizardX
+1 to both your and monkut's answers... they'd be perfect combined :-)
Jarret Hardie
Nice, I wasn't familiar with the urllib2.Request object. This maps better to Therms PHP.
monkut