2011-08-23 3 views
7

私はWikipediaにログインするための簡単なスクリプトを書こうとしており、Mediawiki APIを使って自分のユーザーページでいくつかのアクションを実行しようとしています。しかし、私は決して最初のログイン要求(このページから:https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Logging_in)を通過するように見えません。私が設定したセッションCookieが送信されているとは思わない。これは、これまでの私のコードです:httpヘッダーのセッションクッキーをpython urllib2で渡しますか?

import Cookie, urllib, urllib2, xml.etree.ElementTree 

url = 'https://en.wikipedia.org/w/api.php?action=login&format=xml' 
username = 'user' 
password = 'password' 

user_data = [('lgname', username), ('lgpassword', password)] 

#Login step 1 
#Make the POST request 
request = urllib2.Request(url) 
data = urllib.urlencode(user_data) 
login_raw_data1 = urllib2.urlopen(request, data).read() 

#Parse the XML for the login information 
login_data1 = xml.etree.ElementTree.fromstring(login_raw_data1) 
login_tag = login_data1.find('login') 
token = login_tag.attrib['token'] 
cookieprefix = login_tag.attrib['cookieprefix'] 
sessionid = login_tag.attrib['sessionid'] 

#Set the cookies 
cookie = Cookie.SimpleCookie() 
cookie[cookieprefix + '_session'] = sessionid 

#Login step 2 
request = urllib2.Request(url) 
session_cookie_header = cookieprefix+'_session='+sessionid+'; path=/; domain=.wikipedia.org; HttpOnly' 

request.add_header('Set-Cookie', session_cookie_header) 
user_data.append(('lgtoken', token)) 
data = urllib.urlencode(user_data) 

login_raw_data2 = urllib2.urlopen(request, data).read() 

私はこの問題はrequest.add_header('Set-Cookie', session_cookie_header)ラインのどこかにあると思うが、私は確かに知りません。これらのPythonライブラリを使用して、すべてのリクエスト(多くのAPI関数に必要)でヘッダー内のCookieを送信するにはどうすればよいですか。

答えて

14

requestsの最新バージョンはsessionsのサポート(だけでなく、使用が本当に簡単で、一般的に偉大であることを)持っている:

with requests.session() as s: 
    s.post(url, data=user_data) 
    r = s.get(url_2) 
+0

私はそれで行きますよ。はるかに簡単です。ありがとうございました! –

関連する問題