【发布时间】:2015-09-22 15:55:11
【问题描述】:
我正在尝试将 html 字符串插入 BeautifulSoup 对象。如果我直接插入它,bs4 会清理 html。如果获取 html 字符串并从中创建汤,并插入我在使用 find 函数时遇到问题。 SO 上的This post thread 建议插入 BeautifulSoup 对象可能会导致问题。我正在使用该帖子中的解决方案,并在每次插入时重新创建汤。
但肯定有更好的方法将 html 字符串插入汤中。
编辑:我将添加一些代码作为问题所在的示例
from bs4 import BeautifulSoup
mainSoup = BeautifulSoup("""
<html>
<div class='first'></div>
<div class='second'></div>
</html>
""")
extraSoup = BeautifulSoup('<span class="first-content"></span>')
tag = mainSoup.find(class_='first')
tag.insert(1, extraSoup)
print mainSoup.find(class_='second')
# prints None
【问题讨论】:
-
你能展示一下你的
html和预期的结果吗? -
@user3100115 如果有帮助,我添加了一些非常简单的代码作为示例。
-
嗨,您是否找到了无需创建新标签的解决方案?
标签: python beautifulsoup