【问题标题】:Beautiful Soup - Iterate table rowsBeautiful Soup - 迭代表行
【发布时间】:2020-07-15 07:10:33
【问题描述】:

我正在使用 BeautifulSoup 和 Python 来读取表格。该表有很多行,每行中有很多 <td> 元素。我正在尝试获取每行中第一个 <td> 元素的文本。

r = requests.get(url)

soup = BeautifulSoup(r.text, 'html.parser')

rows = soup.find_all('tr')
for row in rows:
    row.find('td').text

我收到以下错误...

AttributeError: 'NoneType' object has no attribute 'text'

这个错误对我来说很有趣,因为通过以下内容,我得到了我想要的数据

rows[1].find('td').text.strip()

显然我只得到一行数据,我需要得到数千行。我确定这是我忽略的非常简单的事情,但我花了几个小时试图解决这个问题。

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    出现属性错误是因为某些行没有 'td' 元素。 试试这个。

    for row in rows:
        if len(row.find_all('td')) >= 1:
            row.find('td').text
    

    【讨论】:

    • 非常感谢。做到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2021-02-28
    • 2017-12-07
    • 1970-01-01
    • 2015-11-08
    • 2017-06-30
    • 2019-04-01
    相关资源
    最近更新 更多