如何将新标签插入BeautifulSoup对象? [英] How can I insert a new tag into a BeautifulSoup object?

查看:137
本文介绍了如何将新标签插入BeautifulSoup对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让我了解BS的html构建.

Trying to get my head around html construction with BS.

我正在尝试插入新标签:

I'm trying to insert a new tag:

self.new_soup.body.insert(3, """<div id="file_history"></div>""")   

当我检查结果时,我得到:

when I check the result, I get:

&lt;div id="file_histor"y&gt;&lt;/div&gt;

所以我要插入一个为Websafe html清理过的字符串.

So I'm inserting a string that being sanitised for websafe html..

我希望看到的是:

<div id="file_history"></div>

如何在ID为file_history的位置3插入新的div标签?

How do I insert a new div tag in position 3 with the id file_history?

推荐答案

使用工厂方法创建新元素:

Use the factory method to create new elements:

new_tag = self.new_soup.new_tag('div', id='file_history')

并插入它:

self.new_soup.body.insert(3, new_tag)

这篇关于如何将新标签插入BeautifulSoup对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆