在Python中使用BeautifulSoup的replaceWith替换HTML标签时遇到问题

1 投票
1 回答
3026 浏览
提问于 2025-04-16 02:39

我在用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'

我在循环的上面部分对node做同样的替换,结果是正确的。我猜可能是因为在遍历节点时,额外的迭代导致了问题。

我哪里做错了,或者有没有更好的方法来解决这个问题?谢谢!

顺便说一下,我在使用Python 2.5和BeautifulSoup 3.0.8.1,都是为了Google Appengine。

1 个回答

1

错误信息是:

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

这个错误出现在BeautifulSoup.py的第131行。它说self.parent是空的(None)。

看看周围的代码,self应该等于你的代码中的node,因为node正在调用它的replaceWith方法。(注意:错误信息提到的是node.replaceWith,但你发的代码显示的是n.replaceWith。你发的代码和错误信息不对应。)所以很明显node.parent是空的。

你可以通过在调用node.replaceWith之前的某个地方放入

if node.parent is not None:

来避免这个错误。

补充:我建议你使用print语句来检查当node.parent是空的时候,你在HTML的哪个位置(也就是错误发生的地方)。可以试试print node.contentsprint node.previous.contents或者print node.next.contents来看看你的位置。一旦你看到HTML,可能就会明白是什么情况导致node.parent变成了None

撰写回答