AttributeError: 'ResultSet' object has no attribute 'find_all' - pd.read_html

AttributeError: 'ResultSet' object has no attribute 'find_all' - pd.read_html

我正在尝试从网页的 table 中提取数据,但一直收到上述错误。我查看了本网站以及其他网站上的示例,但 none 直接解决了我的问题。请看下面的代码:

from bs4 import BeautifulSoup

import requests

import pandas as pd

url = 'http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2'

r = requests.get(url)

data = r.text

soup = BeautifulSoup(data, "lxml")

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

rows = table.find_all('tr')[2:]

data = {
    'RK' : [],
    'PLAYER' : [],
    'TEAM' : [],
    'GP' : [],
    'G' : [],
    'A' : [],
    'PTS' : [],
    '+/-' : [],
    'PIM' : [],
    'PTS/G' : [],
    'SOG' : [],
    'PCT' : [],
    'GWG' : [],
    'G1' : [],
    'A1' : [],
    'G2' : [],
    'A2' : []
}

for row in rows:
    cols = row.find_all('td')
    data['RK'].append( cols[0].get_text() )
    data['PLAYER'].append( cols[1].get_text() )
    data['TEAM'].append( cols[2].get_text() )
    data['GP'].append( cols[3].get_text() )
    data['G'].append( cols[4].get_text() )
    data['A'].append( cols[5].get_text() )
    data['PTS'].append( cols[6].get_text() )
    data['+/-'].append( cols[7].get_text() )
    data['PIM'].append( cols[8].get_text() )
    data['PTS/G'].append( cols[9].get_text() )
    data['SOG'].append( cols[10].get_text() )
    data['PCT'].append( cols[11].get_text() )
    data['GWG'].append( cols[12].get_text() )
    data['G1'].append( cols[13].get_text() )
    data['A1'].append( cols[14].get_text() )
    data['G2'].append( cols[15].get_text() )
    data['A2'].append( cols[16].get_text() )

df = pd.DataFrame(data)

df.to_csv("NHL_Players_Stats.csv")

我已经消除了错误,看到错误是指 table(即结果集)没有方法 find_all 并通过评论获得了代码 运行输出以下行:

#rows = table.find_all('tr')[2:]

并改变这个:

for row in rows:

但是,这不会从网页中提取任何数据,只是创建一个包含列 headers 的 .csv 文件。

我尝试使用 soup.find_all 将一些数据直接提取到行中,但出现以下错误;

    data['GP'].append( cols[3].get_text() )
IndexError: list index out of range

我没能解决。

因此,我们将不胜感激。

此外,出于好奇,是否有任何方法可以使用以下方法达到预期的结果:

dataframe = pd.read_html('url')

因为,我也试过这个,但请继续保持:

FeatureNotFound: Couldn't find a tree builder with the features you
requested: html5lib. Do you need to install a parser library?

理想情况下,这是我更喜欢的方法,但在网上找不到任何示例。

find_all returns a ResultSet,这基本上是一个元素列表。因此,它没有方法 find_all,因为这是属于单个元素的方法。

如果您只想要一个 table,请使用 find 而不是 find_all 来寻找它。

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

然后,获取其行应该像您已经完成的那样工作:

rows = table.find_all('tr')[2:]

你得到的第二个错误是因为,由于某种原因,table 的其中一行似乎只有 3 个单元格,因此你的 cols 变量变成了一个只有索引 0 的列表, 1 和 2。这就是为什么 cols[3] 给你一个 IndexError.

就使用以下方法实现相同结果而言: 数据框 = pd.read_html('url')

它是通过使用或类似的方式实现的: dataframe = pd.read_html(url, header=1, index_col=None)

我之前收到错误的原因是因为我没有在 'Preferences'.

中将 Spyder 的 iPython 控制台后端配置为 'automatic'

不过,我仍在尝试使用 BeautifulSoup 解决此问题。因此,任何有用的意见将不胜感激。