【问题标题】:pass session cookies in http header with python urllib2?使用 python urllib2 在 http 标头中传递会话 cookie?
【发布时间】:2011-11-02 00:49:03
【问题描述】:

我正在尝试使用 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 函数都是必需的)。

【问题讨论】:

    标签: python http cookies wikipedia-api


    【解决方案1】:

    最新版本的requests 支持sessions(而且使用起来非常简单且总体上很棒):

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

    【讨论】:

    • 我会同意的。这要容易得多。谢谢!
    猜你喜欢
    • 2012-03-17
    • 2016-11-26
    • 2011-12-12
    • 1970-01-01
    • 2010-10-25
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多