python - NameError BeautifulSoup HTML 解析
问题描述
我编写的代码旨在从本地目录中的多个 .html 文件中搜索和删除具有特定类的 div 标签(递归)。蟒蛇 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 代码格式(就地),使其具有可读性和美观性,并带有适当的缩进。如何添加这个功能?
解决方案
这是更正,请记住变量内容是在“if”块中声明的,因为当您在它之外使用 BeautifulSoup 时,变量不是“可见的”/定义的。
#!/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(name) as f: #name instead of fi
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
for div in soup.find_all('div', {'class': 'sidebar'}):
div.decompose()
推荐阅读
- vb.net - 如何使用 For Each 循环将一组控件连续实例化到我的表单上?
- php - 如何将数据库查询构建器转换为 Eloquent 模型
- graphql - 来自结构化对象的 Typeorm 动态查询构建器
- excel-formula - 寻找变量变化的值
- jquery - 在与 v-for @click 方法不同的 vue 组件中调用函数
- c# - 在 PC 上找不到 monodevelop
- clojure - 找不到 clojure/data/json:如何让我的 REPL 看到这个(和类似的)依赖项
- java - AsyncTask 的结果未发布到 Activity 的 TextView
- ruby - 使用 `pi = x * sin(180 / x)` 计算 PI 的值
- sql-server - 使用 LEVENSHTEIN 算法匹配字符串