用 beautifulsoup 我得到了一个网站的 html 代码,假设是这样的:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
如何使用 beautifulsoup 在 head 标签内添加此行 body {background-color:#b0c4de;}?
假设 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;}')
但是你应该create a <style> tag之前。
例如:
head = soup.head
head.append(soup.new_tag('style', type='text/css'))
head.style.append('body {background-color:#b0c4de;}')
