【发布时间】:2021-10-31 09:23:32
【问题描述】:
我编写的代码旨在从本地目录中的多个 .html 文件中搜索和删除具有特定类的 div 标记(递归)。 Python 2.7
#!/usr/bin/python
from bs4 import BeautifulSoup
import os
root = '/path/to/directory/test'
for (dirpath, dirs, files) in os.walk(root):
for name in files:
if name.endswith('.html'):
with open(fi) as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
for div in soup.find_all('div', {'class': 'sidebar'}):
div.decompose()
返回错误:
File "./parser.py", line 14, in <module>
soup = BeautifulSoup(content, 'html.parser') NameError: name 'content' is not defined
我对 python 还很陌生:如何解决它?最后,我想添加一个漂亮的 HTML 代码格式(就地),使其具有可读性和美观性,并带有适当的缩进。如何添加这个功能?
【问题讨论】:
-
for 循环从未见过以
.html结尾的文件名,因此从未分配过content。 -
最后三行应该在 if 块中
标签: python html python-2.7 beautifulsoup