我试图将一个html字符串插入一个BeautifulSoup对象。如果直接插入,bs4会清理html。如果获取html字符串并从中创建一个soup,并插入我在使用find
函数时遇到问题。This post threadon因此建议插入美化组对象可能会导致问题。我用的是那篇文章中的溶液,每次插入时都会重新制作汤。
但肯定有更好的方法将html字符串插入soup中。
编辑:我将添加一些代码作为问题所在的示例
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字符串,就是插入另一个BeautifulSoup对象。
输出:
更新1
这个怎么样?想法是使用BeautifulSoup生成右AST节点(span标记)。看起来这避免了“无”问题。
输出:
最好的方法是创建一个新标记} 方法的作用。
span
,并将其插入到您的mainSoup
。这就是^{相关问题 更多 >
编程相关推荐