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

Python调用Yfinance接口获取股票推荐趋势遇403错误求助

解决Yfinance推荐趋势数据获取403错误及Flask路由问题

问题分析

  1. 403 Forbidden错误:Yahoo Finance的API会校验请求的User-Agent标识,直接用requests.get发起请求时,默认请求头会被识别为非浏览器请求,从而被拦截。
  2. Flask路由参数问题:原代码中get_recommendations函数定义了symbol参数,但路由规则未传递该参数,会导致Flask无法正确匹配请求。

修正方案

1. 补充请求头绕过反爬验证

添加模拟浏览器的请求头,让Yahoo Finance服务器认为请求来自合法浏览器,核心是设置User-Agent和Accept字段。

2. 修正Flask路由参数传递

提供两种参数传递方式,按需选择:

  • 路径参数:将股票代码作为URL路径的一部分(如/get_recommendations/AAPL)
  • 查询参数:通过URL查询字符串传递(如/get_recommendations?symbol=AAPL)

修正后的完整代码

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# 方式1:路径参数传递股票代码
@app.route('/get_recommendations/<symbol>', methods=['GET'])
def get_recommendations_path(symbol):
    url = f"https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}?modules=recommendationTrend&corsDomain=finance.yahoo.com&formatted=false"
    # 模拟浏览器请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*'
    }
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return jsonify(response.json())
    else:
        error_msg = f"Failed to fetch data for symbol {symbol}. Status code: {response.status_code}"
        print(error_msg)
        return jsonify({"error": error_msg}), response.status_code

# 方式2:查询参数传递股票代码(二选一即可)
@app.route('/get_recommendations', methods=['GET'])
def get_recommendations_query():
    symbol = request.args.get('symbol')
    if not symbol:
        return jsonify({"error": "Symbol parameter is required"}), 400
    
    url = f"https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}?modules=recommendationTrend&corsDomain=finance.yahoo.com&formatted=false"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*'
    }
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return jsonify(response.json())
    else:
        error_msg = f"Failed to fetch data for symbol {symbol}. Status code: {response.status_code}"
        print(error_msg)
        return jsonify({"error": error_msg}), response.status_code

if __name__ == '__main__':
    app.run(debug=True)

额外说明

  • User-Agent可根据自身常用浏览器版本调整,只要格式符合浏览器标识规范即可。
  • 使用jsonify返回结果,能确保Flask自动设置正确的application/json响应头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:16:24