我想讀取使用請求包保存在github中的文本文件。 這裏是我使用Python代碼:使用python讀取github文件返回HTML標記
import requests
url = 'https://github.com/...../filename'
page = requests.get(url)
print page.text
非但沒有文字的,我讀的HTML標籤。 如何從文件中讀取文本而不是HTML標籤?
我想讀取使用請求包保存在github中的文本文件。 這裏是我使用Python代碼:使用python讀取github文件返回HTML標記
import requests
url = 'https://github.com/...../filename'
page = requests.get(url)
print page.text
非但沒有文字的,我讀的HTML標籤。 如何從文件中讀取文本而不是HTML標籤?
有一些很好的解決方案了,但如果你使用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.')
您可以通過更改您的路段始訪問文本版本
https://raw.githubusercontent.com/
確保你得到你所想 - 什麼,如果你把網址到瀏覽器你? Github通常會返回一個內嵌文件的頁面 - 您可能需要調整您的URL以直接指向該文件。嘗試'https://github.com/repo/raw /.../文件名',它重定向到'https://raw.githubusercontent.com/repo /.../文件名' – brichins
嗨,謝謝你的回覆。我把URL放到瀏覽器中,然後我得到這個文件。無論如何,我也嘗試了https://github.com/repo/raw/.../filename鏈接,我可以通過瀏覽器以原始格式打開文件,但是在通過python閱讀時,我只能獲取HTML標籤。 – Sandy