找到()后replaceWith()不工作(使用BeautifulSoup) [英] find() after replaceWith() doesn't work (using 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 code,我不明白你怎么能代替这个语法别的东西。只要有
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 = BeautifulSoup(s.renderContents())
。然后,你可以找到
试。
Simpler answer : after your call to replaceWith
, regenerate and clean s
by calling s = BeautifulSoup(s.renderContents())
. Then you can find
again.
这篇关于找到()后replaceWith()不工作(使用BeautifulSoup)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!