【问题标题】:Get the content of multiple classes when scraping a website抓取网站时获取多个类的内容
【发布时间】:2021-04-25 05:29:09
【问题描述】:

我面临的问题很简单。如果我想从网站获取一些数据,则有 两个类具有同名。但它们都包含一个包含不同信息的表。我的代码只输出了第一堂课的内容。它看起来像这样:

page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find("tr", {"class": "table3"})
print(results.prettify())

如何获取代码以输出两个表的内容或仅输出第二个表的内容? 提前感谢您的回答!

【问题讨论】:

  • 找到两个元素的 XPath,您可以单独访问它们:geeksforgeeks.org/how-to-use-xpath-with-beautifulsoup
  • 我试过了,但它创建的列表是空的。我不知道为什么网站上的任何元素都会出现这种情况。
  • 您也可以尝试使用 pandas read_html 作为快捷方式 df_list=pd.read_html(url) ,如果您的页面有两个表格,结果将在 df_list 中有两个条目,您可以访问特定表格作为 df_list[0] 或df_list[1]。类似于我对stackoverflow.com/questions/67219371/… 的回复
  • 网址是什么?

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可以使用.find_all()[1] 获得第二个结果。示例:

from bs4 import BeautifulSoup

txt = """
<tr class="table3"> I don't want this </tr>
<tr class="table3"> I want this! </tr>
"""

soup = BeautifulSoup(txt, "html.parser")

results = soup.find_all("tr", class_="table3")
print(results[1])  # <-- get only second one

打印:

<tr class="table3"> I want this! </tr>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多