从雅虎财经废弃大量股票数据时出现问题

问题描述 投票:0回答:1

我想取消雅虎财经的“关键统计”选项卡。 HTML 页面包含我使用 Beautiful Soup 废弃的多个表。每个表仅包含 2 列,我设法使用 HTML 标签 “table、td 和 tr” 和 Pandas 的 “read_html” 函数来废弃它们。

使用此代码将表连接成单个数据帧

 response = requests.get(url, headers={'user-agent': 'custom'})
 soup = BeautifulSoup(response.content, 'html.parser')
 key_stats = pd.DataFrame(columns=["indicator", "value"])
 tables = pd.read_html(str(soup))

 for table in tables:
     table.columns = ['indicator', 'value' ]
     key_stats = pd.concat([key_stats, table], axis=0)
 
 key_stats = key_stats.set_index("indicator")

当使用较小的股票列表时,该代码可以完美运行,但是当尝试对较大的列表(5665 只股票)使用相同的代码时,会出现以下错误。

 ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements

此错误在某些股票上随机出现,这意味着被废弃的表格包含 1 列,这是不正确的。

最令人困惑的部分是,当使用产生错误的相同股票重新执行时,代码可以正常工作。

我不明白是什么导致了这个问题,有人可以帮助我吗?

html web-scraping beautifulsoup yahoo-finance
1个回答
0
投票

正如评论所述,在没有看到 HTML 数据的情况下,我们所知道的是,从雅虎财经的“关键统计数据”选项卡(在此处可见)中抓取的许多股票的数据不一致。这意味着您需要实施一些策略,以便在面对这些不一致时更加稳健:

  • 在将表连接到
    key_stats
    DataFrame 之前,验证每个表确实具有预期的两列。这可以通过检查 DataFrame 的形状来完成。
  • 实现一个 try-except 块来捕获并处理
    ValueError
    。这将允许您记录或调查有问题的库存,而无需中断整个抓取过程。
  • 增强抓取逻辑,以处理页面布局可能不同或某些预期表格不存在的情况。

例如:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "your_yahoo_finance_url"
response = requests.get(url, headers={'user-agent': 'custom'})
soup = BeautifulSoup(response.content, 'html.parser')
key_stats = pd.DataFrame(columns=["indicator", "value"])
tables = pd.read_html(str(soup))

for table in tables:
    try:
        # Validate the table structure
        if table.shape[1] == 2:
            table.columns = ['indicator', 'value']
            key_stats = pd.concat([key_stats, table], axis=0)
        else:
            print("Skipped a table with unexpected format.")
    except ValueError as e:
        print(f"Error processing a table: {e}")

key_stats = key_stats.set_index("indicator")

这样,您的代码会在尝试重命名列并将其连接之前检查每个表是否恰好有两列。
它还捕获在此过程中可能发生的任何

ValueError
,允许您根据需要记录或处理它。
您可以更好地处理所抓取数据的可变性。

© www.soinside.com 2019 - 2024. All rights reserved.