【问题标题】:Reading a github file using python returns HTML tags使用 python 读取 github 文件会返回 HTML 标签
【发布时间】:2019-08-25 21:07:09
【问题描述】:

我正在尝试使用 requests 包读取保存在 github 中的文本文件。 这是我正在使用的python代码:

    import requests
    url = 'https://github.com/...../filename'
    page = requests.get(url)
    print page.text

我读的是 HTML 标签,而不是文本。 如何从文件中读取文本而不是 HTML 标记?

【问题讨论】:

  • 确保你得到你所想的——如果你把那个 URL 放到你的浏览器中,你会得到什么? Github 通常会返回一个嵌入了文件的页面——您可能需要调整您的 URL 以直接指向该文件。试试https://github.com/repo/raw/.../filename,它会重定向到https://raw.githubusercontent.com/repo/.../filename
  • 您好,感谢您的回复。我将 URL 放入浏览器并获取文件。无论如何我也尝试过github.com/repo/raw/.../filename链接,我可以通过浏览器以原始格式打开文件,但是在通过python阅读时,我只得到了HTML标签。

标签: python


【解决方案1】:

已经有一些很好的解决方案,但如果你使用requests,请关注 Github 的API

所有内容的端点是

GET /repos/:owner/:repo/contents/:path

但请记住,Github API 的默认行为是使用 base64 对内容进行编码。

在您的情况下,您将执行以下操作:

#!/usr/bin/env python3
import base64
import requests


url = 'https://api.github.com/repos/{user}/{repo_name}/contents/{path_to_file}'
req = requests.get(url)
if req.status_code == requests.codes.ok:
    req = req.json()  # the response is a JSON
    # req is now a dict with keys: name, encoding, url, size ...
    # and content. But it is encoded with base64.
    content = base64.decodestring(req['content'])
else:
    print('Content was not found.')

【讨论】:

  • 嗨,我试过这个,但我最终得到一个错误提示:ValueError: No JSON object could be decoded
  • 我无法复制您的错误,即使我收到 404 响应(这种情况下的结果是 keyError)。使用 Python 2.7 和 3.4 进行了尝试。你能给我你使用的 URL 或用户、repo 和路径吗?谢谢。
  • 嗨,我认为我构建了错误的 URL,这就是我收到上一个错误的原因。现在我得到了正确的 URL,但我得到了 404 响应。你知道如何避免这种情况吗?感谢您的帮助。
  • 您可以像requests.get(url, headers={'Authorization': 'token {your token}'}) 一样将访问令牌添加到标头,例如:requests.get(url, headers={'Authorization': 'token c7abb397c7abb397c7abb397'})。其他一切都保持不变。您在 Github 设置 -> 个人访问令牌下获得令牌。如果有帮助,请告诉我。
  • content = base64.b64decode(req['content']) 效果更好。
【解决方案2】:

您可以通过将链接的开头更改为

来访问文本版本
https://raw.githubusercontent.com/

【讨论】:

    【解决方案3】:

    感谢@dasdachs 的回答。但是,执行以下行时出现错误:

    content = base64.decodestring(req['content'])
    

    我得到的错误是:

    /usr/lib/python3.6/base64.py in _input_type_check(s)
        511     except TypeError as err:
        512         msg = "expected bytes-like object, not %s" % s.__class__.__name__
    --> 513         raise TypeError(msg) from err
        514     if m.format not in ('c', 'b', 'B'):
        515         msg = ("expected single byte elements, not %r from %s" %
    
    TypeError: expected bytes-like object, not str
    

    因此我将其替换为以下 sn-p:

    content = base64.b64decode(json['content'])
    

    在下面分享我的工作 sn-p(在 Python 3 中执行):

    import requests
    import base64
    import json
    
    
    def constructURL(user = "404",repo_name= "404",path_to_file= "404",url= "404"):
      url = url.replace("{user}",user)
      url = url.replace("{repo_name}",repo_name)
      url = url.replace("{path_to_file}",path_to_file)
      return url
    
    user = '<provide value>'
    repo_name = '<provide value>'
    path_to_file = '<provide value>'
    json_url ='https://api.github.com/repos/{user}/{repo_name}/contents/{path_to_file}'
    
    json_url = constructURL(user,repo_name,path_to_file,json_url) #forms the correct URL
    response = requests.get(json_url) #get data from json file located at specified URL 
    
    if response.status_code == requests.codes.ok:
        jsonResponse = response.json()  # the response is a JSON
        #the JSON is encoded in base 64, hence decode it
        content = base64.b64decode(jsonResponse['content'])
        #convert the byte stream to string
        jsonString = content.decode('utf-8')
        finalJson = json.loads(jsonString)
    else:
        print('Content was not found.')
    
    for key, value in finalJson.items():
        print("The key and value are ({}) = ({})".format(key, value))
    

    【讨论】:

      【解决方案4】:

      扩展@Patrick 的答案,我将向您展示我的代码以了解如何做到这一点。

      import requests
      url = 'https://raw.githubusercontent.com/...'
      page = requests.get(url)
      print page.text
      

      【讨论】:

        【解决方案5】:

        您可以先通过 bash 或使用像 GitPython 这样的 python 库克隆 repo。然后只需在本地打开并读取文件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-03
          • 2020-01-16
          • 2014-03-25
          • 1970-01-01
          相关资源
          最近更新 更多