gpt4 book ai didi

python - 使用 python urllib2 在 http header 中传递 session cookie?

转载 作者:太空狗 更新时间:2023-10-29 21:25:02 25 4
gpt4 key购买 nike

我正在尝试使用 Mediawiki api 编写一个简单的脚本来登录维基百科并在我的用户页面上执行一些操作。但是,我似乎从来没有通过第一个登录请求(来自此页面:https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Logging_in)。我认为我设置的 session 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 库在每个请求的 header 中发送 cookie(这对于许多 API 函数来说是必需的)。

最佳答案

最新版本requests支持 sessions (以及使用起来真的很简单而且通常很棒):

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

关于python - 使用 python urllib2 在 http header 中传递 session cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7162850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com