使用 Beautiful Soup 在网站中使用两个表格进行网页抓取

时间:2021-03-23 17:46:58

标签: python web-scraping beautifulsoup html-table

问:使用美丽的汤提取带有特斯拉季度收入的表并将其存储到名为 tesla_revenue 的数据帧中。数据框应包含日期和收入列。确保从“收入”列中删除逗号和美元符号。

我为此使用以下代码:

chmod: cannot access 'RDP.sh': No such file or directory
/bin/bash: ./RDP.sh: No such file or directory

该代码仅适用于第一个表“特斯拉年收入”,但不检索“特斯拉季度收入”表

给出网址:https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue?cm_mmc=Email_Newsletter-

1 个答案:

答案 0 :(得分:0)

试试这个:

revenue = soup.find_all("table", attrs={"class": "historical_data_table table"})

table = revenue[1]
body = table.find_all("tr")
head = body[0]
body_rows = body[1:]

all_rows = []
for row_num in range(len(body_rows)):
    row = []
    for row_item in body_rows[row_num].find_all("td"):
        clean = row_item.text.replace("$", "").replace(",", "")
        
        row.append(clean)
    all_rows.append(row)

tesla_revenue = pd.DataFrame(data=all_rows, columns=["Date", "Revenue"])
tesla_revenue