【发布时间】: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