从 Python 请求获取 Instagram 重定向?

2024-03-18

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

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

当编码为Requests:

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)

where 客户端ID and 重定向网址是适当的值。这确实会产生 200 HTTP status_code 值,但重定向永远不会作为 post 的结果被调用。同样的方法与urllib产生相同的结果;即使它返回 200 status_code,它也不会调用重定向。

采用完全相同的 URL 命令并将其放入 Chrome 中是成功的,重定向在 Instagram 上完全正常工作。我什至使用成功测试了这一点网页浏览器:

import webbrowser
b = webbrowser.get('chrome')
webbrowser.open(user_AuthRequest_Instagram)

那么为什么Requests方法对这种 URL 重定向情况不起作用吗?


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

我发现自动化此用户身份验证步骤的最佳解决方案是使用类似的东西Bottles并创建一个按钮,其操作是适当的 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 重定向并完成获取令牌。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Python 请求获取 Instagram 重定向? 的相关文章

随机推荐