将html字符串插入BeautifulSoup obj

2024-04-26 03:55:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个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

Tags: 对象字符串divhtmltagfindclassfirst
2条回答

最简单的方法,如果您已经有一个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()

输出:

<div>
 test1
<div>
 insert1
</div>
</div>

更新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')

输出:

<div class="second"></div>

最好的方法是创建一个新标记span,并将其插入到您的mainSoup。这就是^{}方法的作用。

In [34]: from bs4 import BeautifulSoup

In [35]: mainSoup = BeautifulSoup("""
   ....: <html>
   ....:     <div class='first'></div>
   ....:     <div class='second'></div>
   ....: </html>
   ....: """)

In [36]: tag = mainSoup.new_tag('span')

In [37]: tag.attrs['class'] = 'first-content'

In [38]: mainSoup.insert(1, tag)

In [39]: print(mainSoup.find(class_='second'))
<div class="second"></div>

相关问题 更多 >