【发布时间】:2019-07-18 21:00:35
【问题描述】:
我正在尝试从多个 html 文件中获取表格。理想情况下,我有一个列表中的行和列,所以我可以进一步处理它。我是 BeautifulSoup 的新手,但我无法让它工作。我认为主要问题出现在函数返回 None 时,因此无法进一步处理。我尝试了 if 语句,但这没有帮助。我现在的代码:
from bs4 import BeautifulSoup
table_dict = {}
for filename, text in tqdm(lowercase_dict.items()):
soup = BeautifulSoup(text, "lxml")
table = soup.find('table')
table_body = table.find('tbody')
if table_body is not None:
tables = table_body
rows = tables.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
table_dict[filename] = cols
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-304-14ade2e7b2ac> in <module>()
7 tables = table_body
8
----> 9 rows = tables.find_all('tr')
10 for row in rows:
11 cols = row.find_all('td')
AttributeError: 'str' object has no attribute 'find_all'
```
【问题讨论】:
标签: python python-3.x beautifulsoup