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

前端之家收集整理的这篇文章主要介绍了python – 在replaceWith()不起作用后的find()(使用BeautifulSoup)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下 python会话:
  1. >>> from BeautifulSoup import BeautifulSoup
  2. >>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i")
  3. >>> myi.replaceWith(BeautifulSoup("was"))
  4. >>> s.find("i")
  5. >>> s = BeautifulSoup("<p>This <i>is</i> a <i>test</i>.</p>"); myi = s.find("i")
  6. >>> myi.replaceWith("was")
  7. >>> s.find("i")
  8. <i>test</i>

请注意第4行后s.find(“i”)的缺失输出

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

编辑:实际上,该示例未演示usecase,它是:

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

每当插入的部分包含非常重要的HTML代码时,我都不会看到如何用其他东西替换这种语法.只是拥有

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

将替换实体的html特殊字符.

解决方法

更简单的答案:在你调用replaceWith之后,通过调用s = BeautifulSoup(s.renderContents())来重新生成和清理s.然后你可以找到.

猜你在找的Python相关文章