首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >美汤:'ResultSet‘对象没有'find_all’属性?

美汤:'ResultSet‘对象没有'find_all’属性?
EN

Stack Overflow用户
提问于 2014-06-09 00:56:12
回答 2查看 86.2K关注 0票数 41

我正在试着用美汤刮一张简单的桌子。下面是我的代码:

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'

我已经阅读了大约12个关于这个错误的StackOverflow问题,但我找不出我做错了什么。

EN

回答 2

Stack Overflow用户

发布于 2014-06-09 01:06:40

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

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

Stack Overflow用户

发布于 2014-06-09 01:13:33

迭代表并使用rowfind_all('td')

   for row in table:
        col = row.find_all('td')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24108507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档