网页爬取时出现AttributeError: 'NoneType'对象无'text'属性求助
解决爬取Yahoo Finance时的AttributeError: 'NoneType' object has no attribute 'text'错误
问题原因
报错核心是soup.find()未找到目标元素,返回了None,后续直接调用.text属性触发了AttributeError,常见诱因有三个:
- 请求头不完整,服务器返回异常页面(比如反爬拦截)
- 目标页面HTML结构已更新,你使用的标签和类名不再匹配
- 目标内容是JavaScript动态加载的,静态请求无法获取
解决方案
1. 验证请求有效性
解析页面前先检查请求状态码,确认服务器正常返回页面:
html = requests.get("https://finance.yahoo.com/quote/BSPAX", headers=headers) print(html.status_code) # 正常应返回200
若状态码不是200,补充请求头字段模拟真实浏览器请求:
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" }
2. 调整元素定位方式
Yahoo Finance页面结构易变动,依赖样式类名定位不稳定,改用更可靠的属性(如data-field)定位目标元素:
price_element = soup.find("fin-streamer", {"data-field": "regularMarketPrice"})
该属性专门标记实时价格字段,比样式类名更不易变化。
3. 增加异常处理逻辑
先判断元素是否存在,避免直接访问None的属性:
if price_element: try: price = float(price_element.text) A1 = [price] print(A1) except ValueError: print("价格文本无法转换为浮点数") else: print("未找到目标价格元素,请检查页面结构")
修改后的完整代码
import requests from bs4 import BeautifulSoup import numpy as np headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" } html = requests.get("https://finance.yahoo.com/quote/BSPAX", headers=headers) if html.status_code != 200: print(f"请求失败,状态码:{html.status_code}") else: soup = BeautifulSoup(html.text, "html.parser") price_element = soup.find("fin-streamer", {"data-field": "regularMarketPrice"}) if price_element: try: A1 = [float(price_element.text)] print(A1) except ValueError: print("无法解析价格为浮点数") else: print("未找到价格元素,请确认页面结构是否更新")
内容的提问来源于stack exchange,提问作者bjdesa
相关产品推荐
相关产品推荐

