find() after replaceWith() doesn#39;t work (using BeautifulSoup)(replaceWith() 后的 find() 不起作用(使用 BeautifulSoup))
问题描述
请考虑以下 python 会话:
Please consider the following 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") 的缺失输出!
Please note the missing output of s.find("i") after line 4!
这是什么原因?有解决办法吗?
What's the reason for this? Is there a workaround?
实际上,该示例并未演示用例,即:
Actually, the example doesn't demonstrate the usecase, which is:
myi.replaceWith(BeautifulSoup("wa<b>s</b>"))
每当插入的部分包含自己重要的 html 代码时,我看不出如何用其他内容替换此语法.只是有
Whenever the inserted part contains itself nontrivial html code, I don't see how you could replace this syntax with something else. Just having
myi.replaceWith("wa<b>s</b>")
将用实体替换 html 特殊字符.
will replace the html special chars by entities.
推荐答案
更简单的答案:调用 replaceWith
后,通过调用 s 重新生成并清理
.然后你就可以再次s
= BeautifulSoup(s.renderContents())find
了.
Simpler answer : after your call to replaceWith
, regenerate and clean s
by calling s = BeautifulSoup(s.renderContents())
. Then you can find
again.
这篇关于replaceWith() 后的 find() 不起作用(使用 BeautifulSoup)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:replaceWith() 后的 find() 不起作用(使用 BeautifulSoup)


基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01