Python爬取Yahoo Finance个股关键统计页面返回404错误如何解决
雅虎财经key-statistics页面爬取返回404问题排查
问题描述
我尝试从雅虎财经的如下URL爬取数据:https://finance.yahoo.com/quote/AAPL/key-statistics?p=AAPL,运行下方Python代码后,得到了对应的HTML响应:
import numpy as np import pandas as pd from bs4 import BeautifulSoup import requests, lxml from lxml import html stockStatDict = {} stockSymbol = 'AAPL' URL = 'https://finance.yahoo.com/quote/'+ stockSymbol + '/key-statistics?p=' + stockSymbol page = requests.get(URL) print(page.text)
返回的HTML内容如下:
<!DOCTYPE html> <html lang="en-us"><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <title>Yahoo</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <style> html { height: 100%; } body { background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%; background-size: cover; height: 100%; text-align: center; font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif; } table { height: 100%; width: 100%; table-layout: fixed; border-collapse: collapse; border-spacing: 0; border: none; } h1 { font-size: 42px; font-weight: 400; color: #400090; } p { color: #1A1A1A; } #message-1 { font-weight: bold; margin: 0; } #message-2 { display: inline-block; *display: inline; zoom: 1; max-width: 17em; _width: 17em; } </style> <script> document.write('<img src="//geo.yahoo.com/b?s=1197757129&t='+new Date().getTime()+'&src=aws&err_url='+encodeURIComponent(document.URL)+'&err=%<pssc>&test='+encodeURIComponent('%<{Bucket}cqh[:200]>')+'" width="0px" height="0px"/>');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+new Date().getTime()+"&src=aws&err_url="+encodeURIComponent(document.URL)+"&err=%<pssc>&test="+encodeURIComponent('%<{Bucket}cqh[:200]>'); </script> </head> <body> <!-- status code : 404 --> <!-- Not Found on Server --> <table> <tbody><tr> <td> <img src="https://s.yimg.com/rz/p/yahoo_frontpage_en-US_s_f_p_205x58_frontpage.png" alt="Yahoo Logo"> <h1 style="margin-top:20px;">Will be right back...</h1> <p id="message-1">Thank you for your patience.</p> <p id="message-2">Our engineers are working quickly to resolve the issue.</p> </td> </tr> </tbody></table> </body></html>
我爬取同一站点下概要tab对应的URL https://finance.yahoo.com/quote/AAPL?p=AAPL 时完全正常,对应代码如下:
import numpy as np import pandas as pd from bs4 import BeautifulSoup import requests, lxml from lxml import html stockDict = {} stockSymbol = 'AAPL' URL = 'https://finance.yahoo.com/quote/'+ stockSymbol + '?p=' + stockSymbol page = requests.get(URL) print(page.text) soup = BeautifulSoup(page.content, 'html.parser') stock_data = soup.find_all('table') for table in stock_data: trs = table.find_all('tr') for tr in trs: tds = tr.find_all('td') if len(tds) > 0: stockDict[tds[0].get_text()] = [tds[1].get_text()] stock_sum_df = pd.DataFrame(data=stockDict) print(stock_sum_df.head()) print(stock_sum_df.info())
请问我哪里操作有误?我目前使用的是雅虎财经免费版本,不知道是否会对该情况产生影响。
问题解答
这个问题和你操作无关,也和免费版权益没有关系,本质是雅虎财经不同路径的反爬规则不同:
- 站点首页、个股概要页对请求头的校验非常宽松,默认requests自带的UA标识可以正常通过校验拿到数据
- 而key-statistics这类子路径要求请求必须携带符合浏览器规范的User-Agent请求头,没有合法UA的请求会被直接拦截,返回你拿到的404错误页
修复方案很简单,给请求添加浏览器UA头即可,修改后的请求代码示例:
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } page = requests.get(URL, headers=headers)
补充说明:如果添加UA后依然解析不到对应统计数据,是因为该页面部分数据是前端异步加载的,静态HTML不会包含完整数据,你可以改用模拟浏览器的工具加载页面,或者直接使用雅虎财经的第三方Python工具包获取数据,无需自行编写解析逻辑。
内容的提问来源于stack exchange,提问作者byteme1776
相关产品推荐
相关产品推荐

