如何使用python urllib2在http头中传递会话cookie?

7 投票
1 回答
9281 浏览
提问于 2025-04-17 00:12

我正在尝试写一个简单的脚本,用来登录维基百科,并在我的用户页面上执行一些操作,使用的是Mediawiki的API。不过,我总是无法通过第一次登录请求(来自这个页面:https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Logging_in)。我觉得我设置的会话cookie没有被发送。以下是我目前的代码:

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库,在每次请求的头部发送cookie(这对于很多API功能来说是必要的)呢?

1 个回答

14

最新版本的 requests 库支持 会话(而且使用起来非常简单,整体来说也很棒):

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

撰写回答