简体   繁体   English

Python请求和Instagram

[英]Python requests and instagram

I am playing around with the instagram api and requests, trying to get past the OAuth. 我在玩instagram api和请求,试图超越OAuth。 I use r = requests.get(...) and follow the instagram doc. 我使用r = requests.get(...)并遵循instagram doc。 However, the output from requests is never what I expect. 但是,请求的输出绝不是我期望的。 I am having 2 issues that are somewhat similar. 我遇到2个有点相似的问题。

1) If I send the wrong parameters I expect to get back JSON looking like 1)如果我发送了错误的参数,我希望得到的JSON看起来像

{"code": 400, "error_type": "OAuthException", "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

Which is what I see if I paste the string from r.url into the browser. 这是我将r.url的字符串粘贴到浏览器中看到的。 However r.json() simply fails and gives me 但是r.json()只是失败了,给了我

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

2) A correct response should redirect me to my redirect url, which will also include a code. 2)正确的回复应将我重定向到我的重定向URL,其中还将包括代码。 Again, this works correctly when pasting r.url into a browser. 同样,将r.url粘贴到浏览器中时,此方法可以正常工作。 I am successfully redirected as expected. 我已成功按预期重定向。 Requests does not appear to redirect me, even with explicitly set allow_redirects=False . 即使显式设置了allow_redirects=False ,请求也似乎没有重定向我。 I only need to read the code from the url. 我只需要从url中读取代码。 How can I get requests to give me the final url for me to extract the code? 我如何获得请求以提供最终的URL供我提取代码?

Edit: Might as well include some code. 编辑:可能还包括一些代码。

def get_code(client_id, redirect_uri, scope="basic"):
    params = {"client_id": client_id,
              "redirect_uri": redirect_uri,
              "response_type": "code",
              "scope": scope}
    r = requests.get('https://api.instagram.com/oauth/authorize/',
                     params=params)
    # print r.url
    # print r.json()
    return r

It tells you in the documentation exactly what happen, At this point, we present the user with a login screen and then a confirmation screen where to grant your app access to her Instagram data , if you run the snippet below you will see a login box in your browser: 它会在文档中准确告诉您发生了什么, 这时,我们向用户显示一个登录屏幕,然后是一个确认屏幕,在此处向您的应用授予访问她的Instagram数据的权限 ,如果运行下面的代码段,则会看到一个登录框在您的浏览器中:

import requests
import  webbrowser
from tempfile import NamedTemporaryFile
params = {"client_id": client_id,
          "redirect_uri": redirect_uri,
          "response_type": "code",
          "scope": scope}
with NamedTemporaryFile(dir=".", delete=0) as f:
    r = requests.get('https://api.instagram.com/oauth/authorize/',
                     params=params)
    f.write(r.content)
    webbrowser.open(f.name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM