You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python快速下载GitHub上的大体积JSON文件?

解决Python从GitHub下载大文件速度过慢的问题

核心原因

GitHub的原始文件服务器(raw.githubusercontent.com)可能对Python请求库的默认请求头进行限速,同时默认的请求模式未启用连接复用或流传输,导致下载效率远低于浏览器。


解决方案1:添加浏览器请求头+流模式下载

模拟浏览器的请求标识,并用流模式分段写入文件,既避免内存占用过高,又绕过服务器的限速策略:

import requests

url = 'https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json'
# 可在浏览器开发者工具Network面板查看自己的User-Agent替换
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}

with requests.get(url, headers=headers, stream=True) as r:
    r.raise_for_status()  # 捕获请求错误
    with open('large-file.json', 'wb') as f:
        # 按8KB分段写入,可根据网络情况调整chunk_size
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

解决方案2:配置连接池复用TCP连接

手动配置requests会话的连接池,复用TCP连接减少握手开销,进一步提升大文件下载效率:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

url = 'https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}

# 创建会话并配置连接池和重试策略
session = requests.Session()
retry_strategy = Retry(
    total=3,
    backoff_factor=0.1,
    allowed_methods=["GET"]
)
adapter = HTTPAdapter(
    max_retries=retry_strategy,
    pool_connections=10,
    pool_maxsize=10
)
session.mount('https://', adapter)

with session.get(url, headers=headers, stream=True) as r:
    r.raise_for_status()
    with open('large-file.json', 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

解决方案3:直接调用系统curl命令(推荐)

系统自带的curl工具默认启用了HTTP/2、连接复用等优化策略,下载速度和浏览器基本一致:

import subprocess

url = 'https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json'
# 调用curl下载,-o指定输出文件名
subprocess.run(['curl', '-o', 'large-file.json', url], check=True)

内容的提问来源于stack exchange,提问作者Jonathan Levi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:36:07