您可能想阅读BeautifulSoup:
import bs4# load the filewith open("existing_file.html") as inf: txt = inf.read() soup = bs4.BeautifulSoup(txt)# create new linknew_link = soup.new_tag("link", rel="icon", type="image/png", href="img/tor.png")# insert it into the documentsoup.head.append(new_link)# save the file againwith open("existing_file.html", "w") as outf: outf.write(str(soup))给定一个像
<html><head> <title>Test</title></head><body> <p>What's up, Doc?</p></body></html>
这产生
<html><head><title>Test</title><link href="img/tor.png" rel="icon" type="image/png"/></head><body><p>What's up, Doc?</p></body></html>
(注意:它已经给空白加上了小节,但是html结构正确了)。



