BeautifulSoup - 替换字符串不起作用

时间:2017-03-19 03:19:12

标签: python beautifulsoup

我有一个NavigableString类型的节点,我想替换内容。根据文档,它应该是这样的:

node.string = 'new string'

然而,如果我检查它不起作用:

print unicode(node)        ---> prints 'old string'
node.string = 'new string'
print unicode(node)        ---> should print 'new string' but prints 'old string'

任何想法?

1 个答案:

答案 0 :(得分:2)

您需要使用replace_with()方法来替换字符串。

从官方文档中可以看出

  

您无法在适当的位置编辑字符串,但可以使用replace_with()

将一个字符串替换为另一个字符串
node.string.replace_with("new string")

您可以查看here

修改

正如您所提到的,nodeNavigableString,您无需更改其.string属性。你应该做 -

node = "new string"

如果节点是tag,那么您应该更改其.string属性。