使用BeautifulSoup从html表获取信息时出错

多赫蒂

我正在尝试使用BeautifulSoup从HTML文档中的表中获取信息并将其放入数据框。我编写了以下代码:

from bs4 import BeautifulSoup
from nltk.corpus import wordnet as wn
import pandas as pd

filename = input('Please enter HTML filename: ')


with open(filename, encoding = "UTF-8") as f_input:
    html = f_input.read()

f = BeautifulSoup(html, "html.parser")


table = f.find_all("table")

n_columns = 0
n_rows = 0
column_names = []

for row in table.find_all('tr'):
    td_tags = row.find_all('td')
    if len(td_tags)>0:
    n_rows+=1
    if n_columns == 0:
       n_columns = len(td_tags)

th_tags = row.find_all('th')
if len(th_tags) > 0 and len(column_names) ==0:
    for th in th_tags:
        column_names.append(th.get_text())

if len(column_names) > 0 and len(column_names) != n_columns:
    raise Exception("Column titles do not match the number of columns")

columns = column_names if len(column_names)> 0 else range(0,n_columns)

df = pd.DataFrame(columns = columns,
                 index=range(0,n_rows))
row_marker = 0
for row in table.find_all('tr'):
    column_marker = 0
    columns = row.find_all('td')
    for column in columns:
        df.iat[row_marker,column_marker] = column.get_text()
        column_marker += 1
    if len(columns)>0:
        row_marker += 1
    for col in df:
        try:
            df[col]=df[col].astype(float)
        except ValueError:
            pass
return df

它提出了以下错误:

AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

我已经阅读了很多,但我仍然不明白我在做什么错。我认为我不应该使用find()谁能帮忙解释一下?

阿内什·杜格(Aneesh Durg)

我相信您的错误来自以下几行:table = f.find_all(“ table”)... table.find_all('tr')中的行:

请注意,表格现在是其中具有表格的一组元素(在某种程度上类似于列表)。如果只有一个表,则可以使用table [0]或在第一次调用中使用find而不是find_all来访问它。如果页面中有一个以上的表,或者您的表可能不是第一个表,则可能需要更深入地研究集合,并查看表中是否有可以唯一标识它的表。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章