【问题标题】:Get file contents from GitHub using Requests and Github API使用 Requests 和 Github API 从 GitHub 获取文件内容
【发布时间】:2020-02-22 06:35:30
【问题描述】:

我正在尝试从 GitHub 获取文件的内容 - 使用 Python 请求和 GitHub API。尽管内容对我来说看起来像 JSON,但当我以编程方式检查时,它说它不是 JSON 格式,我无法从中获取 JSON 数据。这是我到目前为止所拥有的(对于我的一小部分 URls):

这是我尝试过的两个网址,但都失败了:

import requests

from requests.exceptions import HTTPError
from json.decoder import JSONDecodeError

myurl = 'https://github.com/bitpod-io/arsenal/blob/a5af2f9bff13d8b6c6592437a19a712edb49ecb0/tests/utils/samplePolicies.json'
myurl = 'https://github.com/yasuhisa1984/achieve/blob/fa6334c484ee9e7c08e2d280fa16ec5bba5f2369/vendor/bundle/gems/fog-aws-1.2.1/lib/fog/aws/iam/default_policy_versions.json'

token = 'mylongtoken'

    try:
        #response = requests.get(myurl, headers={'Authorization': 'token {}'.format(token), 'Accept': 'application/vnd.github.v3.raw'})
        response = requests.get(myurl, headers={'Authorization': 'token {}'.format(token)})

        response.raise_for_status()
    except HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')
    except Exception as err:
        print(f'Some other error occurred: {err}')
    else:
        print('Success')
        print(response.headers)
        if 'json' in response.headers.get('Content-Type'):
            try:
                resp_json = response.json()
            except JSONDecodeError:
                print(f'Unable to get data in JSON format.')
            else:
                print(resp_json)
        else:
            print('Response content is not in JSON format.')

如果我在某个地方错了,谁能告诉我。我想使用 API 将文件内容作为文本或 json(首选)获取。

【问题讨论】:

    标签: python-requests github-api


    【解决方案1】:

    确保您从“原始”内容 URL 下载,而不是 HTML github 页面。我相信这是您想要的原始 JSON 文件的 URL:

    https://raw.githubusercontent.com/yasuhisa1984/achieve/master/vendor/bundle/gems/fog-aws-1.2.1/lib/fog/aws/iam/default_policy_versions.json

    以下代码适用于该 URL:

    import requests
    url = "https://raw.githubusercontent.com/yasuhisa1984/achieve/master/vendor/bundle/gems/fog-aws-1.2.1/lib/fog/aws/iam/default_policy_versions.json"
    resp = requests.get(url)
    data = resp.json()
    

    【讨论】:

    • 我仍然收到同样的错误:“响应内容不是 JSON 格式。”我的 requests.get() 公式是否正确?
    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 2020-08-01
    相关资源
    最近更新 更多