从Python请求中获取Instagram重定向? [英] Getting Instagram redirect from Python Requests?

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

问题描述

在为Instagram执行OAuth2时,存在以下形式的重定向调用:

https://api.instagram.com/oauth/authorize/?client_id=<XXX>&redirect_uri=<YYY>&response_type=code&scope=basic+likes+comments

使用请求编码

s = requests.Session()

###Create URL call with query parameters
user_AuthRequest_Instagram = 'https://api.instagram.com/oauth/authorize/?client_id=' + Client_ID + '&redirect_uri=' + redirect_URL + '&response_type=code&scope=basic+likes+comments'

###Get the result of this URL
r = s.get(user_AuthRequest_Instagram, allow_redirects=True, timeout=120)

###Checking results
print(r.status_code, r.url, r.cookies, r.text)

其中CLIENT_IDREDIRECT_URL是适当的值。这确实会产生一个200的HTTP STATUS_CODE值,但POST永远不会调用重定向。使用urllib的相同方法会产生相同的结果;它从不调用重定向,即使它返回200 STATUS_CODE。

使用完全相同的URL命令并将其放入Chrome中是成功的,重定向在Instagram上完全有效。我甚至使用WebBrower

成功地进行了测试
import webbrowser
b = webbrowser.get('chrome')
webbrowser.open(user_AuthRequest_Instagram)

那么为什么请求方法对此URL重定向案例不起作用?

推荐答案

解决此问题的方法是在Instagram身份验证过程的第一步为服务器端(显式)情况获取OAuth2令牌,要求用户从其浏览器发送初始帖子。此要求解释了我在请求中遇到的问题,因为当Web浏览器工作时,这些请求在浏览器环境之外。

我发现自动化这一用户身份验证步骤的最佳解决方案是使用瓶子之类的东西,并创建一个按钮,其操作是适当的Instagram调用。如下所示:

    from bottle import Bottle, run, route, request, response, template, redirect

    @app.route('/BestTag_Auth')
    def user_Auth_Instagram():
       #Initializations
       Scope_Lst = 'basic+likes+comments+public_content'

       #Create link for user to authorize BestTag
       user_AuthRequest_Instagram = 'https://api.instagram.com/oauth/authorize/?client_id=' + <Client_ID> + '&redirect_uri=' + <redirect_URL> + '&response_type=code&scope=' + Scope_Lst   

       #Send Web page with button to user
       location_URL = "location.href='" + user_AuthRequest_Instagram + "';" 
       auth_Button = '<input type="button" onclick="' + location_URL + '" value="Get authorization" />'

       return auth_Button

然后您可以使用类似的方法来捕获Instagram重定向并完成令牌的获取。

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

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