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.
我找到了一個PHP腳本,可以讓我按照我在SO問題中的要求做。我可以很好地使用它,但出於好奇,我想在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?
我當然可以使用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']);
2 个解决方案
#1
Similar to monkut's answer, but a little more concise.
類似於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
It returns the cookie jar, which you can use in other requests. Just pass it to the HTTPCookieProcessor constructor.
它返回cookie jar,您可以在其他請求中使用它。只需將其傳遞給HTTPCookieProcessor構造函數即可。
monkut's answer installs a global HTTPCookieProcessor, which stores the cookies between requests. My solution does not modify the global state.
monkut的答案安裝了一個全局HTTPCookieProcessor,它在請求之間存儲cookie。我的解決方案不會修改全局狀態。
#2
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)).
我不熟悉PHP,但這可能會讓你開始。我在這里安裝了開啟器,它將把它應用到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)