将html字符串插入BeautifulSoup对象

Pre*_*eom 4 python beautifulsoup

我试图将html字符串插入BeautifulSoup对象。如果我直接将其插入,bs4会清理html。如果采用html字符串并从中创建汤,然后插入我在使用该find功能时遇到的问题。SO上的该帖子主题表明,插入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
Run Code Online (Sandbox Code Playgroud)

Mat*_*ing 5

如果您已经有一个html字符串,最简单的方法是插入另一个BeautifulSoup对象。

from bs4 import BeautifulSoup

doc = '''
<div>
 test1
</div>
'''

soup = BeautifulSoup(doc, 'html.parser')

soup.div.append(BeautifulSoup('<div>insert1</div>', 'html.parser'))

print soup.prettify()
Run Code Online (Sandbox Code Playgroud)

输出:

<div>
 test1
<div>
 insert1
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

更新1

这个怎么样?想法是使用BeautifulSoup生成正确的AST节点(span标签)。看起来这避免了“无”问题。

import bs4
from bs4 import BeautifulSoup

mainSoup = BeautifulSoup("""
<html>
    <div class='first'></div>
    <div class='second'></div>
</html>
""", 'html.parser')

extraSoup = BeautifulSoup('<span class="first-content"></span>', 'html.parser')
tag = mainSoup.find(class_='first')
tag.insert(1, extraSoup.span)

print mainSoup.find(class_='second')
Run Code Online (Sandbox Code Playgroud)

输出:

<div class="second"></div>
Run Code Online (Sandbox Code Playgroud)