【问题标题】:Problem using replaceWith to replace HTML tags with BeautifulSoup on PythonPython上使用replaceWith用BeautifulSoup替换HTML标签的问题
【发布时间】:2010-08-11 18:56:48
【问题描述】:

我在 Python 中使用 BeautifulSoup,在替换某些标签时遇到了麻烦。我正在寻找<div> 标签并检查儿童。如果这些孩子没有孩子(是 NODE_TYPE = 3 的文本节点),我将它们复制为 <p>

from BeautifulSoup import Tag, BeautifulSoup

class bar:

 self.soup = BeautifulSoup(self.input)
 foo()
 def foo(self):    
  elements = soup.findAll(True)

  for node in elements:

    # ....other stuff here if not <div> tags.

    if node.name.lower() == "div":
      if not node.find('a'):
        newTag = Tag(self.soup, "p")
        newTag.setString(node.text)
        node.replaceWith(newTag)
        nodesToScore.append(newTag)
      else:
        for n in node.findAll(True):
          if n.getString():  # False if has children
            newTag = Tag(self.soup, "p")
            newTag.setString(n.text)
            n.replaceWith(newTag)

我收到一个 AttributeError:

  File "file.py", line 125, in function
    node.replaceWith(newTag)
  File "BeautifulSoup.py", line 131, in replaceWith
    myIndex = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'

我在 for 循环中对node 进行了相同的替换,它可以正常工作。我假设它有问题,因为通过节点作为 n 的额外迭代。

我做错了什么,或者有什么更好的方法来做到这一点?谢谢! PS。我将 Python 2.5 用于 Google Appengine 和 BeautifulSoup 3.0.8.1

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    错误提示:

        myIndex = self.parent.index(self)
    AttributeError: 'NoneType' object has no attribute 'index'
    

    此代码出现在 BeautifulSoup.py 的第 131 行。 它说self.parent 是无。

    查看周围的代码显示self 应该等于您的代码中的node,因为node 正在调用它的replaceWith 方法。(注意:错误消息显示node.replaceWith,但您发布的代码显示n.replaceWith。您发布的代码与错误消息/回溯不对应。)所以显然node.parent 是None。

    你可以通过放置来避免错误

    if node.parent is not None:
    

    在调用 node.replaceWith 之前的代码中的某个点。

    编辑:我建议您使用print 语句来调查当node.parent 为无时您在HTML 中的位置(即错误发生的位置)。也许使用print node.contentsprint node.previous.contentsprint node.next.contents 来查看您的位置。一旦您看到 HTML,可能会很明显您所处的病理情况导致 node.parent 变为 None

    【讨论】:

    • 感谢您注意到node.replaceWithn.replaceWith。我在引用的地方添加了附加代码。当else 不存在时,if not 运行良好,这就是为什么我认为它不相关但我错了。
    • @feesta:不看 HTML 就很难调试。我添加了一个编辑(上图),建议您如何找到与问题对应的 HTML。
    • @~ubuntu 谢谢!它现在正在工作!我添加了 if node.parent is None: (log node) else: (the rest) 我发现错误的 HTML 是 div 标签,只有空格。这是我要剥离的一部分。再次感谢!
    • @feesta:啊,是的!这是调试它的好方法;比我的建议好。两个竖起大拇指:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2014-03-09
    • 2021-08-01
    • 2023-03-28
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多