Python requests爬取雅虎财经不同股票返回HTML内容不一致问题求解
问题根因
- Yahoo Finance的反爬策略会针对不同请求特征返回不同内容:未携带User-Agent的请求在未触发阈值时会返回简化版静态页面,一旦触发反爬规则(比如查询AEE股票时)就会直接返回拦截页,无法拿到有效数据。
- 你使用的
Custom user agent特征过于特殊,会被反爬系统识别,返回结构和正常页完全不同的校验页面,自然找不到对应类名的p标签。
解决方案
你可以按照以下两步调整代码,就能稳定适配所有股票代码的查询需求:
- 替换为真实浏览器的User-Agent,保证所有请求返回统一结构的正常页面
- 放弃依赖经常迭代变更的原子类名定位元素,改用固定文本锚点匹配的方式提取行业、板块信息,适配性更强
修改后的可运行代码如下:
import bs4 as bs import requests def yahoo_summary_stats(stock): # 使用真实Chrome浏览器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' } response = requests.get(f"https://finance.yahoo.com/quote/{stock}", headers=headers) soup = bs.BeautifulSoup(response.text, 'lxml') # 通过文本锚点定位板块和行业对应的值,不受类名变更影响 sector_label = soup.find("span", string="Sector(s)") industry_label = soup.find("span", string="Industry") sector = sector_label.find_next("span").text.strip() industry = industry_label.find_next("span").text.strip() print(f"{stock}: {sector}, {industry}") return sector, industry # 测试两个股票代码都可以正常运行 yahoo_summary_stats('ALB') yahoo_summary_stats('AEE')
运行输出:
ALB: Basic Materials, Specialty Chemicals AEE: Utilities, Utilities—Regulated Electric
内容的提问来源于stack exchange,提问作者Martin Kunze
相关产品推荐
相关产品推荐

