Python请求:如何从302重定向获取响应cookie [英] Python Requests : How to get response cookie from 302 redirect

查看:1073
本文介绍了Python请求:如何从302重定向获取响应cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行自动化,该过程将通过instagram api发送http请求来关注或取消关注用户,现在我正在使用Python Requests模块,而Im正在尝试通过网站' http://pikore.com 。我当前的代码是:

I'm trying to make an automation that will send the http requests to follow or unfollow a user through an instagram api, right now I'm using the Python Requests module and Im trying to do it through the site 'http://pikore.com'. My current code is is :

import requests
from requests.auth import HTTPBasicAuth

s = requests.Session()
s.get('http://pikore.com')

print(s.cookies)
s.get('http://www.pikore.com/session/new?from=%2F', auth=HTTPBasicAuth('USERNAME', 'USERSECRET'))
pikore_session = s.cookies['_pikore_session']
print(s.cookies)
s.get('http://pikore.com')
print(s.cookies)

cookies = {
'_pikore_session': pikore_session,
'token': 'BAhJIjcyNTY5NDczOTIuZWIxM2FlYi41Mjc3ZTI4NjI4ZDM0NDRlOGRjNWNjZmFjNWU3YmJmYgY6BkVU--9b52c6305368f28c83ffc288e9d55e94b3e864db',
}

headers = {
    'Host': 'www.pikore.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0',
    'Referer': 'http://www.pikore.com/nike',
}

print(s.get('http://www.pikore.com/follow/13460080', headers=headers, cookies=cookies))
s.get('http://www.pikore.com/')
print(s.cookies)

所以这可行并且将执行给定的请求,唯一的事情是,授权行只会获取 _pikore_session cookie,而不会获取我想要获取的令牌cookie。
通过instagram授权重定向登录后,它将重定向您3次,最后您将登陆网站并登录,但是在第三个重定向上,我可以看到它输出了令牌响应cookie,我希望有人得到它,这样我就不必每次手动获取它。

So this works and will carry out the given request, the only thing is, the authorization line will only get the '_pikore_session' cookie, but not the token cookie, which I want to get. After you log in through the instagram authorization redirect, it will redirect you three times and then finally you'll land on the website, logged in, but on the third redirect, I can see that it outputs the 'token' response cookie, I want to someone get that so that I dont have to go and get it each time manually.

推荐答案

我今天尝试解决此问题,发现请求中的相关错误

I was trying to solve this today and found a relevant bug in requests.

使用JohnCC330的解决方案关闭 auto_redirect 为我工作:

Using JohnCC330's solution of turning off auto_redirect worked for me:

res = requests.post(
    host,
    data={'somefield':'my value'},
    allow_redirects=False)

if res.status_code == 302: # expected here
    jar = res.cookies
    redirect_URL2 = res.headers['Location']
    res2 = requests.get(redirect_URL2, cookies=jar)
    # res2 is made with cookies collected during res' 302 redirect

希望这会有所帮助,

Bob

这篇关于Python请求:如何从302重定向获取响应cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆