如何用Python从雅虎热门股票页仅抓取股票代码与公司名列?
How to Extract Only Symbol and Company Name from Yahoo Finance Trending Tickers
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-exceptblock catches common issues like network errors or missing tables, making the script more robust.
内容的提问来源于stack exchange,提问作者Lahari
相关产品推荐
相关产品推荐

