使用 beautifulsoup 美化 html 文档的一部分

prettifying a part of the html doc using beautifulsoup

我有一个 html 文档,我想从中提取表格并美化表格。我目前拥有的是:

with open('html.txt','r') as file1:
    read_f=file1.read()
soup = BeautifulSoup(read_f)

the_soup=soup.findAll('table', {'id': 'table_id'})
with open('prettified.txt','w') as f2:
    f2.write(the_soup.prettify())

但是我得到一个错误 prettify is no an attribute。

soup.findAll 将 return 一个包含所有 table 元素的列表。您应该遍历此列表并打印每个匹配的 table:

的美化版本
with open('prettified.txt','w') as f2:
    for table in the_soup:
        f2.write(table.prettify())