2014-06-08 53 views
19

我想用美丽的汤刮一张简单的桌子。这里是我的代码:美丽的汤:'ResultSet'对象没有属性'find_all'?

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上关于此错误的问题看,我想不出什么我我做错了。

+0

如果你给*全回溯它会是有用的*,你有很多的'.find_all's目前并没有大家都想/可以运行这段代码自己找出来... –

+0

对不起。我编辑了这篇文章 – Anton

回答

9
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') 

你可能想遍历td S IN在这里排,而不是整个表。 (否则,你就只能看到第一行了个遍。)

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

table变量包含数组。你需要在其成员上调用find_all(即使你知道它是只有一个成员的数组),而不是整个事情。

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

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

for row in table: 
     col = row.find_all('td') 
相关问题