我正在尝试使用请求包读取保存在 github 中的文本文件。这是我正在使用的python代码:
import requests
url = 'https://github.com/...../filename'
page = requests.get(url)
print page.text
Run Code Online (Sandbox Code Playgroud)
我没有获取文本,而是阅读 HTML 标签。如何从文件中读取文本而不是 HTML 标签?
已经有一些很好的解决方案,但是如果您使用requests,请遵循 Github 的API。
所有内容的端点是
GET /repos/:owner/:repo/contents/:path
Run Code Online (Sandbox Code Playgroud)
但请记住,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.')
Run Code Online (Sandbox Code Playgroud)