基于Python BeautifulSoup的雅虎财经行情爬虫近期失效,是否平台有规则调整?
雅虎财经爬虫故障排查结果及修复方案
页面变动确认
雅虎财经近一周未对股票详情页做结构性改版,你遇到的故障不属于页面结构变动导致的解析失效,问题出在请求层。
故障根因
- 请求使用了HTTP协议,雅虎财经已全站强制HTTPS跳转,HTTP请求无法拿到正常页面内容
- 直接使用urlopen发起无请求头的裸请求,被雅虎反爬规则拦截,返回的是gzip压缩的异常内容,未解码直接传入BeautifulSoup会出现乱码,无法解析出任何HTML标签,完全匹配你贴出的运行日志特征
修复方案
1. 调整请求协议
将代码中请求地址前缀的http修改为https
2. 添加标准请求头并处理压缩响应
修改请求逻辑,添加浏览器UA头,同时对压缩后的返回内容做解码处理,参考修改后的核心代码:
import gzip import time from bs4 import BeautifulSoup from urllib.request import Request, urlopen retry = 0 def get_fy(ticker, outFile): global retry try: p1 = "https://finance.yahoo.com/quote/" p2 = "?p=" # 构造带标准请求头的请求 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", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8" } req_url = p1 + ticker + p2 + ticker req = Request(req_url, headers=headers) r = urlopen(req) # 解码压缩内容 content_encoding = r.info().get("Content-Encoding", "") if "gzip" in content_encoding: html_content = gzip.decompress(r.read()).decode("utf-8") else: html_content = r.read().decode("utf-8") bsObj = BeautifulSoup(html_content, "html5lib") titleList = bsObj.find_all("title") if not titleList or titleList[0].get_text().find('Stock Price')<0: if retry > 2: retry = 0 return False retry += 1 time.sleep(10) return get_fy(ticker,outFile) retry = 0 elements = bsObj.find_all("td") # 后续解析逻辑保持不变
修改完成后即可正常拿到页面标签,后续原有解析逻辑可正常运行。
内容的提问来源于stack exchange,提问作者john colburn
相关产品推荐
相关产品推荐

