我正在用 Python 3.1.2 编写一个脚本,该脚本登录到一个站点,然后开始发出请求。我可以毫不费力地登录,但在登录之后,请求会返回一个错误,说明我还没有登录。我的代码如下所示:
import urllib.request
from http import cookiejar
from urllib.parse import urlencode
jar = cookiejar.CookieJar()
credentials = {'accountName': 'username', 'password': 'unenc_pw'}
credenc = urlencode(credentials)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
urllib.request.install_opener(opener)
req = opener.open('http://www.wowarmory.com/?app=armory?login&cr=true', credenc)
test = opener.open('http://www.wowarmory.com/auctionhouse/search.json')
print(req.read())
print(test.read())
第一个请求的响应是我希望在登录时得到的页面。
对第二个的响应是:
b'{"error":{"code":10005,"error":true,"message":"You must log in."},"command":{"sort":"RARITY","reverse":false,"pageSize":20,"end":20,"start":0,"minLvl":0,"maxLvl":0,"id":0,"qual":0,"classId":-1,"filterId":"-1"}}'
我是否缺少某些东西来使用我从成功身份验证中获得的任何 cookie 信息来处理 future 的请求?
最佳答案
我曾经遇到过这个问题。我无法让 cookie 管理自动工作。让我沮丧了好几天,我最终手动处理了 cookie。那就是从响应 header 中获取“Set-Cookie”的内容,并将其保存在安全的地方。随后,向该服务器发出的任何请求,我都会使用我之前获得的值将“Cookie”设置到请求 header 中。
关于python - 在 Python3 中使用 cookie 处理程序处理站点请求的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4194245/