开发者

What is the proper way to handle site requests with cookie handlers in Python3?

开发者 https://www.devze.com 2023-01-25 14:05 出处:网络
I\'m writing a script in Python 3.1.2 that logs into a site and then begins to make requests. I can log in without any great difficulty, but after doing that the requests return an error stating I hav

I'm writing a script in Python 3.1.2 that logs into a site and then begins to make requests. I can log in without any great difficulty, but after doing that the requests return an error stating I haven't logged in. My code looks like this:

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())

The response to the first request is the page I expect to get when logging in.

The response to the second is:

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"}}'

Is there something I'm missing to use any cookie information I have from successful auth开发者_开发百科entication for future requests?


I had this issue once. I can't get the cookie the cookie management working automatically. Frustrated me for days, I ended up handling the cookie manually. That is getting the content of 'Set-Cookie' from the response header, saving it somewhere safe. Subsequently, any request made to that server, I will set the 'Cookie' into the request header with the value I got earlier.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号