Python爬取Yahoo Finance收盘价返回空列表问题排查
解决Yahoo Finance股票收盘价爬取返回空列表的问题
你遇到的空列表问题主要有两个核心原因:
- Yahoo Finance的历史数据表格是动态渲染的,直接用
requests请求只能拿到静态HTML框架,页面里没有实际的行情数据行; - 原代码里的表格class选择器
W(100%) M(0)已经失效,页面结构更新后定位不到正确的表格。
下面给你两种可行的解决方案:
方案一:用yfinance库(推荐,更稳定)
Yahoo官方推荐用这个第三方库获取财经数据,不用爬页面,直接调用接口可靠性更高。
- 先安装库:
pip install yfinance
- 示例代码:
import yfinance as yf ticker = input('Enter the ticker symbol: ') # 初始化股票对象 stock = yf.Ticker(ticker) # 获取历史数据,可指定周期(比如'1mo'=1个月,'1y'=1年,'max'=全部历史) hist_data = stock.history(period='1mo') # 提取收盘价转为列表 close_prices = hist_data['Close'].tolist() print(close_prices)
方案二:用Selenium处理动态页面(坚持爬虫的话)
如果一定要通过爬页面的方式获取,需要用Selenium加载完整的动态页面:
- 安装依赖:
pip install selenium
(需额外下载对应浏览器的驱动,比如Chrome的chromedriver,确保版本和浏览器匹配)
- 示例代码:
from selenium import webdriver from bs4 import BeautifulSoup import time ticker = input('Enter the ticker symbol: ') url = f'https://finance.yahoo.com/quote/{ticker}/history?p={ticker}' # 初始化Chrome浏览器 driver = webdriver.Chrome() driver.get(url) time.sleep(3) # 等待页面完全加载 # 获取渲染后的页面源码 soup = BeautifulSoup(driver.page_source, 'html.parser') driver.quit() # 定位历史数据表格(当前页面的表格class是historical-data-table) table = soup.find('table', class_='historical-data-table') if not table: print('未找到历史数据表格') else: close_prices = [] # 跳过表头行,遍历数据行 for row in table.find_all('tr')[1:]: cells = row.find_all('td') if len(cells) >= 5: try: # 收盘价在第5个单元格(索引4) price_str = cells[4].text.replace(',', '') close_prices.append(float(price_str)) except ValueError: print('解析收盘价失败') print(close_prices)
内容的提问来源于stack exchange,提问作者CoderScrub
相关产品推荐
相关产品推荐

