Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

How to scrape table data from HTML?

$
0
0

I have been trying to scrape a table from this website https://www.alphaquery.com/stock/aapl/earnings-historybut in no way I can achieve it. I can t even find the table.

import requestsfrom bs4 import BeautifulSoupdef get_eps(ticker):    url = f"https://www.alphaquery.com/stock/{ticker}/earnings-history"    page = requests.get(url)    soup = BeautifulSoup(page.content, 'html.parser')    # Attempt to more robustly find the table by checking for specific headers    table = None    for table_candidate in soup.find_all("table"):        headers = [th.get_text(strip=True) for th in table_candidate.find_all("th")]        if "Estimated EPS" in headers:            table = table_candidate            break    if table:        rows = table.find_all('tr')[1:6]          for row in rows:            cells = row.find_all('td')            if len(cells) >= 4:  # Ensure there are enough columns in the row                try:                    est_eps = cells[2].text.strip().replace('$', '').replace(',', '')                except ValueError:                    continue  # Skip rows where conversion from string to float fails    else:        print(f"Failed to find earnings table for {ticker}")    return est_eps# Example usageticker = 'AAPL'beats = get_eps(ticker)print(f'{ticker}  estimates {est_eps}')

Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>