加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 将html字符串插入到BeautifulSoup对象中

发布时间:2020-12-20 11:44:06 所属栏目:Python 来源:网络整理
导读:我试图将一个 HTML字符串插入到BeautifulSoup对象中.如果我直接插入它,bs4清理html.如果使用html字符串并从中创建一个汤,并插入我使用find函数时遇到问题. This post thread on SO表明插入BeautifulSoup对象可能会导致问题.我正在使用该帖子的解决方案,并在
我试图将一个 HTML字符串插入到BeautifulSoup对象中.如果我直接插入它,bs4清理html.如果使用html字符串并从中创建一个汤,并插入我使用find函数时遇到问题. This post thread on 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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读