Python 如何在 BeautifulSoup 对象中插入新标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21356014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:39:19  来源:igfitidea点击:

How can I insert a new tag into a BeautifulSoup object?

pythonbeautifulsoup

提问by Jay Gattuso

Trying to get my head around html construction with BS.

试图通过 BS 了解 html 结构。

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;

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

所以我插入了一个为 websafe html 消毒的字符串..

What I expect to see is:

我希望看到的是:

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

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

如何div在位置 3插入一个带有 id的新标签file_history

采纳答案by Birei

Use the factory method to create new elements:

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

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

and insert it:

并插入它:

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

回答by Guy Gavriely

See the documentation on how to append a tag:

请参阅有关如何附加标签的文档:

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>

回答by Hieu

Other answers are straight off from the documentation. Here is the shortcut:

其他答案直接来自文档。这是快捷方式:

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)