2014-01-25 17 views
13

試圖讓我的頭與BS的HTML建設。如何將新標籤插入BeautifulSoup對象?

我試圖插入一個新的標籤:

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

當我檢查的結果,我得到:

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

所以我將一個字符串,被消毒的網絡安全HTML ..

我希望看到的是:

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

如何在位置3插入一個新的div標籤,編號爲file_history

回答

7

使用工廠方法來創建新的元素:

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

,並插入:

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

啊,好的。謝謝。這是一個兩步過程,我試圖欺騙。讚賞。 –

20

參見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> 
7

其他的答案是直開來文檔。這裏是快捷方式:

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)