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)
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
