Python 如何将新标记插入到BeautifulSoup对象中?

Python 如何将新标记插入到BeautifulSoup对象中?,python,beautifulsoup,Python,Beautifulsoup,试图让我的头脑了解如何用BS构建html 我正在尝试插入一个新标记: self.new_soup.body.insert(3, """<div id="file_history"></div>""") 因此,我插入了一个字符串,该字符串将针对websafe html进行清理 我希望看到的是: <div id="file_history"></div> 如何在位置3插入新的div标记,id为file\u history?使用工厂方法创建

试图让我的头脑了解如何用BS构建html

我正在尝试插入一个新标记:

self.new_soup.body.insert(3, """<div id="file_history"></div>""")   
因此,我插入了一个字符串,该字符串将针对websafe html进行清理

我希望看到的是:

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


如何在位置3插入新的
div
标记,id为
file\u history

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

new_tag = self.new_soup.new_tag('div', id='file_history')
并插入:

self.new_soup.body.insert(3, new_tag)
请参阅以下文档:

soup=beautifulsou(“”)
原始标签=汤
新标签=汤。新标签(“a”,href=”http://www.example.com")
原始标签。附加(新标签)
原始标签
# 
new_tag.string=“链接文本。”
原始标签
# 

其他答案直接来自文档。以下是捷径:

from bs4 import BeautifulSoup

temp_soup = BeautifulSoup('<div id="file_history"></div>')
# BeautifulSoup automatically add <html> and <body> tags
# There is only one 'div' tag, so it's the only member in the 'contents' list
div_tag = temp_soup.html.body.contents[0]
# Or more simply
div_tag = temp_soup.html.body.div
your_new_soup.body.insert(3, div_tag)
从bs4导入美化组
温度汤=美丽汤(“”)
#BeautifulSoup自动添加和标记
#只有一个'div'标记,因此它是'contents'列表中唯一的成员
div_tag=temp_soup.html.body.contents[0]
#或者更简单地说
div_tag=temp_soup.html.body.div
你的新汤。主体。插入(3,div_标签)

啊,好的。谢谢这是一个分两步的过程,我试图作弊。谢谢。
soup = BeautifulSoup("<b></b>")
original_tag = soup.b

new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.example.com"></a></b>

new_tag.string = "Link text."
original_tag
# <b><a href="http://www.example.com">Link text.</a></b>
from bs4 import BeautifulSoup

temp_soup = BeautifulSoup('<div id="file_history"></div>')
# BeautifulSoup automatically add <html> and <body> tags
# There is only one 'div' tag, so it's the only member in the 'contents' list
div_tag = temp_soup.html.body.contents[0]
# Or more simply
div_tag = temp_soup.html.body.div
your_new_soup.body.insert(3, div_tag)