【问题标题】:BeautifulSoup how to only return class objectsBeautifulSoup 如何只返回类对象
【发布时间】:2020-11-12 03:38:56
【问题描述】:

我有一个类似于此的html 文档:

<div class='product'>
    <table>
        <tr>
            random stuff here
        </tr>
        <tr class='line1'>
            <td class='row'>
                <span>TEXT I NEED</span>
            </td>
        </tr>
        <tr class='line2'>
            <td class='row'>
                <span>MORE TEXT I NEED</span>
            </td>
        </tr>
        <tr class='line3'>
            <td class='row'>
                <span>EVEN MORE TEXT I NEED</span>
            </td>
        </tr>
    </table>
</div>

所以我使用了这段代码,但我从 tr 中得到第一个不是类的文本,我需要忽略它:

soup.findAll('tr').text

另外,当我尝试只做一个类时,这似乎不是有效的 python:

soup.findAll('tr', {'class'})

我需要一些帮助来提取文本。

【问题讨论】:

    标签: python html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    要获得所需的输出,请使用 CSS 选择器排除第一个 &lt;tr&gt; 标记,然后选择其余部分:

    from bs4 import BeautifulSoup
    
    
    soup = BeautifulSoup(html, 'html.parser')
    
    for tag in soup.select('.product tr:not(.product tr:nth-of-type(1))'):
        print(tag.text.strip())
    

    输出:

    TEXT I NEED
    MORE TEXT I NEED
    EVEN MORE TEXT I NEED
    

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2010-12-27
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2013-03-17
      • 2011-03-26
      • 1970-01-01
      • 2018-05-24
      相关资源
      最近更新 更多