2012-11-09 115 views
1

随着beautifulsoup我得到一个网站的HTML代码,让说,那就是:如何添加背景颜色在html代码中使用beautifulsoup?

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
<h1>My First Heading</h1> 
<p>My first paragraph.</p> 
</body> 
</html> 

我如何加入这一行body {background-color:#b0c4de;}使用beautifulsoup的标签里面?

比方说,Python代码是:

#!/usr/bin/python 

import cgi, cgitb, urllib2, sys 
from bs4 import BeautifulSoup 

site = "www.example.com" 
page = urllib2.urlopen(site) 
soup = BeautifulSoup(page) 
+1

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#modifying-the-tree – 2012-11-09 12:27:42

+0

Tichodroma谢谢你...你可以把它写成答案所以我可以给你最好的答案 – a1204773

回答

6

您可以使用:

soup.head.append('body {background-color:#b0c4de;}') 

,但你应该create a <style> tag之前。

例如:

head = soup.head 
head.append(soup.new_tag('style', type='text/css')) 
head.style.append('body {background-color:#b0c4de;}') 
+0

非常感谢你.. – a1204773