2014-06-08 8 views
19

나는 Beautiful Soup을 사용하여 간단한 테이블을 긁어 내려고합니다. 나는 그것을 실행할 때마다, 나는이 오류를 얻을, 그러나Beautiful Soup : '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 

: :이 오류에 대한 다스 StackOverflow의 질문에 주위를 읽고

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

, 그리고 내가 무엇을 알아낼 수 없습니다 여기 내 코드입니다 잘못하고있다. 이것은 당신에게 결과 집합을 제공

+0

을 사용/이 코드를 실행하여 그 코드를 찾을 수 있습니다 ... –

+0

죄송합니다. 게시물을 수정했습니다. – Anton

답변

9
table = soup.find_all(class_='dataframe') 

- 클래스와 일치 즉 모든 요소. 그 중 하나를 반복하거나, dataFrame이 하나만있는 경우 find을 대신 사용할 수 있습니다. 코드에서이 후자는 당신이 즉시 문제를 해결하기 위해 필요한 것 같다 :

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

당신은 아마에 td의 반복 할 : 그러나

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

, 그게 전부가 아니다 전체 테이블이 아닌 여기의 행. (그렇지 않으면 당신은 반복 첫 번째 행을 확인할 수 있습니다.)를 table 변수가 배열을 포함

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

. 전체 구성원이 아닌 구성원에 대해 find_all을 호출해야합니다 (구성원이 하나 뿐인 배열 인 경우에도). 당신은 * 전체 역 추적을 준 경우가 있고 모두가에 원하는 .find_all`s`을 많이 가지고 그것은 * 유용 할 것

>>> 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') 
관련 문제