【问题标题】:using beautifulsoup to get second and third child in BeautifuSoup [duplicate]使用beautifulsoup在BeautifulSoup中获取第二个和第三个孩子[重复]
【发布时间】:2016-08-24 01:21:08
【问题描述】:

我有一个类似于下面的表格:

<table>
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        <tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

我需要每行的第二个和第三个。我在 Python 3.5 中使用 BeautifulSoup

现在,我正在做:

Table = Soup.find('table', attrs={'id': 'field'})
        Tbody = Table.find('tbody')
        Records = Tbody.find_all('tr')
        Record = Records.find_all('td')
        for field in Records:
            print (Record[2].text)

我收到错误:

Traceback (most recent call last):
  File "C:/Users/arcee/PycharmProjects/scraper/main.py", line 33, in <module>
    Record = Records.find_all('td')
AttributeError: 'ResultSet' object has no attribute 'find_all'

有没有更简单的方法来获取第二个和第三个 TD 元素?

谢谢

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    由于这些行,您会收到该错误:

    Records = Tbody.find_all('tr')
    Record = Records.find_all('td')
    

    find_all 返回搜索标签出现次数的list (ResultSet)。 ResultSet 没有 find_all 属性 - 但它的每个成员都有。所以,做..

    Records = Tbody.find_all('tr')
    for record in records:
        print(record.find_all('td'))
    

    将使您的代码运行。

    【讨论】:

    • 好的。这很好。非常感谢
    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    相关资源
    最近更新 更多