我目前正在完成一项使用 python 创建 HTML 文件的作业。我了解如何将 HTML 文件读入 python,然后编辑并保存它。
table_file = open('abhi.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()
上述部分的问题在于它只是替换了整个 HTML 文件并将字符串放入 write() 中。我怎样才能编辑文件并同时保持其内容完好无损。我的意思是,写这样的东西,但是在 body 标签
里面<link rel="icon" type="image/png" href="img/tor.png">
我需要链接自动进入开始和结束 body 标签之间。
最佳答案
您可能想要 read up on 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 结构是正确的)。
关于python - 使用 Python 编辑和创建 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355225/