You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从雅虎热门股票页仅抓取股票代码与公司名列?

Hey there! Let's adjust your code to pull just the stock symbols and company names you need from the trending tickers table. Here's a reliable way to do it:

Key Fixes & Improvements

First, the original class selector for the table might break if Yahoo updates their styling classes. Instead, we'll use a more stable attribute (data-test) to target the table—this is designed for testing purposes and rarely changes. Then we'll explicitly extract only the first two columns (Symbol and Company Name) from each row.

Modified Code

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://finance.yahoo.com/trending-tickers'

# Add basic error handling to catch request issues
try:
    r = requests.get(url)
    r.raise_for_status()  # Raise an error if the request fails (e.g., 404, 500)
    soup = BeautifulSoup(r.text, 'html.parser')

    # Locate the table using the stable data-test attribute
    table = soup.find("table", {"data-test": "fin-list-table"})
    
    if not table:
        print("Oops! Couldn't find the trending tickers table. The page structure might have changed.")
    else:
        # Skip the header row and get all data rows
        data_rows = table.find_all("tr")[1:]
        
        # Initialize a list to store our targeted data
        ticker_info = []
        
        for row in data_rows:
            cells = row.find_all("td")
            # Extract symbol (1st cell) and company name (2nd cell)
            symbol = cells[0].text.strip()
            company_name = cells[1].text.strip()
            ticker_info.append({
                "Symbol": symbol,
                "Company Name": company_name
            })
        
        # Convert to a DataFrame for easy viewing/export
        df = pd.DataFrame(ticker_info)
        print(df)

except requests.exceptions.RequestException as e:
    print(f"Failed to fetch the page: {str(e)}")

Why This Works

  • Stable Table Selection: Using data-test="fin-list-table" avoids issues with dynamic CSS classes that Yahoo might update.
  • Targeted Column Extraction: We explicitly grab the first two <td> elements from each row, which correspond to the Symbol and Company Name columns in the trending tickers table.
  • Error Handling: The try-except block catches common issues like network errors or missing tables, making the script more robust.

内容的提问来源于stack exchange,提问作者Lahari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:39:59