2009-06-11 51 views
0

我發現了一個PHP腳本,可以讓我做我在this SO問的問題。我可以使用這個很好,但出於好奇,我想在Python中重新創建下面的代碼。如何在Python中重新創建這個PHP代碼?

我當然可以使用urllib2來獲取頁面,但是我對如何處理cookie自從機械化(在Windows上使用Python 2.5和2.6進行測試以及在Ubuntu上使用Python 2.5進行測試...都是最新的機械化版本)似乎打破了頁面。我如何在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']); 
+0

2.6呵?爲什麼不嘗試3? – 2009-06-11 23:13:50

+0

@Beau Martinez引用freenode #python頻道中的話題「現在使用python 3.x太早」 – baudtack 2009-06-11 23:18:11

+0

Beau,3.x有很多不一致之處(比如看一下wsgiref)。從2.x移動到3.x(使用2to3)很容易,但無法輕易走向另一條路。 – 2009-06-11 23:20:12

回答

6

到monkut的答案相似,但多了幾分簡潔。

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 

它返回cookie jar,您可以在其他請求中使用它。只需將它傳遞給構造函數HTTPCookieProcessor即可。

monkut的答案安裝了一個全球HTTPCookieProcessor,它在請求之間存儲cookie。我的解決方案不會修改全局狀態。

5

我不熟悉PHP,但這可能會讓你開始。 我在這裏安裝opener,將它應用到urlopen方法。如果你不想'安裝'開啓者,你可以直接使用開啓者對象。 (opener.open(url,data))。

參考: 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)