我目前正在编写一个任务,用于使用python创建HTML文件。我理解如何将HTML文件读入python,然后编辑和保存它。
table_file = open('abhi.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()
上面的问题是,它只是替换了整个HTML文件,并将字符串放入写()中。如何在编辑文件的同时保持其内容完整。我的意思是,写这样的东西,但是在的身体标记中
<link rel="icon" type="image/png" href="img/tor.png">
我需要链接,以自动进入之间的打开和关闭主体标签。
发布于 2016-02-11 21:28:21
你可能想要阅读BeautifulSoup
import bs4
# load the file
with open("existing_file.html") as inf:
txt = inf.read()
soup = bs4.BeautifulSoup(txt)
# create new link
new_link = soup.new_tag("link", rel="icon", type="image/png", href="img/tor.png")
# insert it into the document
soup.head.append(new_link)
# save the file again
with 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结构正确)。
https://stackoverflow.com/questions/35355225
复制相似问题