在 python 中使用 Wget 从 github 下载二进制文件

Downloading binary files from github using Wget in python

我正在创建一个从 GitHub 存储库中获取文件的程序,但 raw.githubusercontent.com 不适用于二进制文件。如果 .ico 文件不是二进制文件,请告诉我如何下载这些文件。

我正在使用 wget.download(),像这样:

import wget
url = “ https://raw.githubusercontent.com/user/repository/branch/file”
wget.download(url)

有什么建议吗?

如果您将 ?raw=true 添加到文件末尾,应该可以。

例如:the .ico for my homepage无法在浏览器中查看

# Original Link
https://github.com/hayesall/hayesall.github.io/blob/master/favicon.ico

# (1) Appended with `?raw=true`
https://github.com/hayesall/hayesall.github.io/blob/master/favicon.ico?raw=true

# (2) Going through githubusercontent
https://raw.githubusercontent.com/hayesall/hayesall.github.io/master/favicon.ico

选项 (1) 或 (2) 可以用 wget:

下载
import wget
url = "https://github.com/hayesall/hayesall.github.io/blob/master/favicon.ico?raw=true"
wget.download(url)
100% [.......................] 1150 / 1150

正在检查下载的文件:

$ file favicon.ico
favicon.ico: MS Windows icon resource - 1 icon, 16x16, 32 bits/pixel

在原子中:

版本信息:

$ wget --version
GNU Wget 1.19.4 built on linux-gnu.
$ pip freeze | grep "wget"
wget==3.2

如果这仍然无效,可能是 wget 的问题(最近更新是在 2015 年)。这是使用 requests:

的替代解决方案
import shutil
import requests

url = "https://raw.githubusercontent.com/hayesall/hayesall.github.io/master/favicon.ico"
req = requests.get(url, stream=True)

assert req.status_code == 200

with open("favicon.ico", "wb") as _fh:
    req.raw.decode_content = True
    shutil.copyfileobj(req.raw, _fh)