【问题标题】:Beautiful Soup: 'ResultSet' object has no attribute 'find_all'?美丽的汤:“ResultSet”对象没有“find_all”属性?
【发布时间】:2014-07-29 07:09:54
【问题描述】:

我正在尝试使用 Beautiful Soup 刮一张简单的桌子。这是我的代码:

import requests
from bs4 import BeautifulSoup

url = 'https://gist.githubusercontent.com/anonymous/c8eedd8bf41098a8940b/raw/c7e01a76d753f6e8700b54821e26ee5dde3199ab/gistfile1.txt'
r = requests.get(url)

soup = BeautifulSoup(r.text)
table = soup.find_all(class_='dataframe')

first_name = []
last_name = []
age = []
preTestScore = []
postTestScore = []

for row in table.find_all('tr'):
    col = table.find_all('td')

    column_1 = col[0].string.strip()
    first_name.append(column_1)

    column_2 = col[1].string.strip()
    last_name.append(column_2)

    column_3 = col[2].string.strip()
    age.append(column_3)

    column_4 = col[3].string.strip()
    preTestScore.append(column_4)

    column_5 = col[4].string.strip()
    postTestScore.append(column_5)

columns = {'first_name': first_name, 'last_name': last_name, 'age': age, 'preTestScore': preTestScore, 'postTestScore': postTestScore}
df = pd.DataFrame(columns)
df

但是,每当我运行它时,我都会收到此错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-116-a900c2872793> in <module>()
     14 postTestScore = []
     15 
---> 16 for row in table.find_all('tr'):
     17     col = table.find_all('td')
     18 

AttributeError: 'ResultSet' object has no attribute 'find_all'

我已经阅读了大约十几个有关此错误的 StackOverflow 问题,但我无法弄清楚我做错了什么。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    table 变量包含一个列表。您需要对其成员调用 find_all(即使您知道这是一个只有一个成员的列表),而不是整个事件。

    >>> type(table)
    <class 'bs4.element.ResultSet'>
    >>> type(table[0])
    <class 'bs4.element.Tag'>
    >>> len(table[0].find_all('tr'))
    6
    >>>
    

    【讨论】:

      【解决方案2】:
      table = soup.find_all(class_='dataframe')
      

      这会给你一个结果集——即所有匹配类的元素。你可以遍历它们,或者,如果你知道你只有一个dataFrame,你可以使用find。从您的代码看来,后者是您处理当前问题所需要的:

      table = soup.find(class_='dataframe')
      

      然而,这还不是全部:

      for row in table.find_all('tr'):
          col = table.find_all('td')
      

      您可能希望遍历此处行中的tds,而不是整个表。 (否则你只会一遍又一遍地看到第一行。)

      for row in table.find_all('tr'):
          for col in row.find_all('td'):
      

      【讨论】:

        【解决方案3】:

        遍历表并使用rowfind_all('td')

           for row in table:
                col = row.find_all('td')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-04-06
          • 2020-11-09
          • 1970-01-01
          • 2016-09-26
          • 1970-01-01
          • 2018-08-06
          • 1970-01-01
          相关资源
          最近更新 更多