【问题标题】:Python parse table from HTML using BeautifulSoupPython 使用 BeautifulSoup 从 HTML 解析表
【发布时间】: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


    【解决方案1】:

    根据您的错误消息,问题在于变量 tables 是一个字符串。尝试不使用 'tbody'。

    for filename, text in tqdm(lowercase_dict.items()):
        soup = BeautifulSoup(text, "lxml")
        table = soup.find('table')
        rows = table.find_all('tr')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2011-06-15
      • 2020-02-06
      • 2014-03-06
      • 2011-07-21
      • 2018-07-10
      • 2013-12-10
      相关资源
      最近更新 更多