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

使用Python获取Yahoo Finance CSV文件时遭遇403错误求助

Yahoo Finance CSV请求返回403错误的原因与解决方法

错误原因

  • Yahoo Finance服务器会校验请求的User-Agent请求头。默认情况下,requests库发送的请求头中,User-Agent值为python-requests/x.x.x(x.x.x为版本号),服务器会识别出这是非浏览器的爬虫请求,因此返回403 Forbidden拒绝访问。
  • 浏览器访问该链接时,会自动携带符合浏览器标识的User-Agent头,服务器识别为合法的浏览器请求,所以允许下载。

解决方法

在请求中添加模拟浏览器的User-Agent头,让服务器认为这是来自浏览器的请求。修改后的代码如下:

import requests

url = "https://query1.finance.yahoo.com/v7/finance/download/BTC-USD?period1=1535760000&period2=1693440000&interval=1d&events=history&includeAdjustedClose=true"

# 添加模拟浏览器的User-Agent请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers)

# 验证请求结果并保存文件
if response.status_code == 200:
    with open("btc-usd-history.csv", "w", encoding="utf-8") as file:
        file.write(response.text)
    print("CSV文件已成功保存")
else:
    print(f"请求失败,状态码:{response.status_code}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:04:57