a12*_*773 1 python beautifulsoup
使用beautifulsoup我得到一个网站的HTML代码,让我们说这是:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
如何使用beautifulsoup body {background-color:#b0c4de;}在head标签内添加此行?
让我们说python代码是:
#!/usr/bin/python
import cgi, cgitb, urllib2, sys
from bs4 import BeautifulSoup
site = "www.example.com"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
您可以使用:
soup.head.append('body {background-color:#b0c4de;}')
但是你之前应该创建一个<style>标签.
例如:
head = soup.head
head.append(soup.new_tag('style', type='text/css'))
head.style.append('body {background-color:#b0c4de;}')