如何使用python在网页抓取中选择第二个元素?

时间:2021-03-21 09:47:13

标签: python web-scraping beautifulsoup tags

我试过了:

    for row in soup.find("tbody").find_all("tr"):
     col = row.find_all("td")
     date =col[0].text
     revenue = col[1].text.replace("$", "").replace(",", "")
    
    tesla_revenue = tesla_revenue.append({"Date":date, "Revenue":revenue}, ignore_index=True)
tesla_revenue.head()

这是结果

<头>
日期 收入
0 2020 31536
1 2019 24578
2 2018 21461
3 2017 11759
4 2016 7000

所以结果显示左边的表格,但我想要右边的表格,我该怎么做才能选择下一个tbody? (截图在链接中)

https://i.stack.imgur.com/3Lepx.png

1 个答案:

答案 0 :(得分:0)

如果你想选择第二个表(<tbody> 标签),你可以这样做:

for row in soup.select("tbody")[1].find_all("tr"):  # <-- note the [1] to select second <tbody>
    # ...