gpt4 book ai didi

python - replaceWith() 后的 find() 不起作用(使用 BeautifulSoup)

转载 作者:太空狗 更新时间:2023-10-29 22:19:40 24 4
gpt4 key购买 nike

请考虑以下 python session :

>>> from BeautifulSoup import BeautifulSoup
>>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i")
>>> myi.replaceWith(BeautifulSoup("was"))
>>> s.find("i")
>>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i")
>>> myi.replaceWith("was")
>>> s.find("i")
<i>test</i>

请注意第 4 行后缺少 s.find("i") 的输出!

这是什么原因?有解决方法吗?

编辑:实际上,该示例并未演示用例,即:

myi.replaceWith(BeautifulSoup("wa<b>s</b>"))

只要插入的部分本身包含重要的 html 代码,我就看不出如何用其他东西替换此语法。刚刚拥有

myi.replaceWith("wa<b>s</b>")

将用实体替换 html 特殊字符。

最佳答案

更简单的答案:调用 replaceWith 后,通过调用 s = BeautifulSoup(s.renderContents()) 重新生成并清理 s。然后您可以再次查找

关于python - replaceWith() 后的 find() 不起作用(使用 BeautifulSoup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com