首页 > 解决方案 > 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 代码格式(就地),使其具有可读性和美观性,并带有适当的缩进。如何添加这个功能?

标签: pythonhtmlpython-2.7beautifulsoup

解决方案


这是更正,请记住变量内容是在“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()

推荐阅读