【问题标题】:NameError BeautifulSoup HTML parseNameError BeautifulSoup HTML 解析
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 另一个错误:File "./parser.py", line 10, in &lt;module&gt; with open(fi) as f: NameError: name 'fi' is not defined
  • 因为正如您在代码中看到的那样,您的整个代码中没有定义“fi”,可能错过了输入名称。这很可能是您的意思with open(name) as f:
  • 你的代码和我的有什么不同?看不出区别。
  • 区别是open(name)而不是open(fi)。作为一个错字,这不应该作为答案输入,问题应该被标记为关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2014-03-06
  • 2011-07-21
  • 2012-12-13
  • 2011-09-24
  • 2018-07-10
  • 2011-01-04
相关资源
最近更新 更多