【问题标题】:How to extract all items from an HTML table with BeautifulSoup4?如何使用 BeautifulSoup4 从 HTML 表中提取所有项目?
【发布时间】:2019-02-19 12:40:17
【问题描述】:

这是我正在抓取的更大网站的一部分的 HTML。:https://pastebin.com/LZ3mJKv0

基本上我希望我的输出是:

Breed: Shih Tzu
Price: $850
Gender: Male
Nickname: Wade
Age: 16 Weeks Old
Color/Markings: red and white
Size at Maturity: Small

等,等等。我已经尝试找到所有 tr 标签、所有 td 标签,并找到所有 b 标签,但没有一个给出我正在寻找的输出或给出错误。

提前感谢您的回复!

【问题讨论】:

    标签: python python-3.x parsing beautifulsoup html-parsing


    【解决方案1】:

    您可以使用嵌套列表推导:

    from bs4 import BeautifulSoup as soup
    d = soup(content, 'html.parser')
    new_results = [[c.text.replace('\n', '') for c in i.find_all('td')] for i in d.find_all('tr')]
    for i in new_results:
      print(' '.join(i))
    

    输出:

    Breed: Shih Tzu
    Price: $850
    Gender: Male Male
    Nickname: Wade
    Age: 16 Weeks Old
    Color/Markings: red and white
    Size at Maturity: Small
    Availability Date: 08/01/2018
    Shipping Area: Pick Up Only
    Payment Method: Credit Cards, Cash
    

    【讨论】:

    • 谢谢你这个工作,但它从其他表中提取,我不希望完整的 html 具有。有没有办法只从某个班级的桌子上拉?我想要的表格包含在 `
      class="properties"> 或者更简单,只需提取具有特定标题的行,比如说我是否只想要品种、价格和年龄?谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2013-02-28
    • 2016-06-20
    • 2019-06-05
    相关资源
    最近更新 更多