如何修改BeautifulSoup中element.strings方法生成的字符串?

时间:2016-02-08 23:36:09

标签: python html string beautifulsoup

当其他标签中有标签时(例如<b>内的<p>),父元素的字符串元素为空,字符串元素是一个生成所有字符串的生成器。

<html>
<body>
<p> First p <b> First b </b>second part first p</p>
<p> Second p <a> first link</a> second part second p <a> second link</a> third part second p</p> 
</body>
</html>

在我的代码中,

soup = BeautifulSoup(html)#text above
ps = soup.find_all('p')
p0 = ps[0]
for s in p0.strings:
    #makes sure that child elements inside <p> tag are skipped
    if s.findParent() == p0:
        s.replace_with('new text')

然而,当我运行时,我得到了

Traceback (most recent call last):
      File "<pyshell#243>", line 1, in <module>
        s.replace_with('new_text')
      File "/usr/lib/python2.7/dist-packages/bs4/element.py", line 211, in replace_with
        my_index = self.parent.index(self)
    AttributeError: 'NoneType' object has no attribute 'index'

第一个字符串p0的文本已更改,但最后一个元素没有更改,因为抛出了错误。同样的事情发生在p1 = ps[1]的第二个元素上。如何分别修改每个字符串元素?我想保留所有现有的标签。

1 个答案:

答案 0 :(得分:0)

这个循环不安全,因为你在迭代时修改p0

for s in p0.strings:

一种安全的方法是在迭代之前为快照p0创建一个列表。

for s in list(p0.strings):