使用 Python 编辑和创建 HTML 文件

Edit and create HTML file using Python

我真的是 Python 的新手。我目前正在处理使用 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">

我需要 link 自动进入开始和结束正文标签之间。

你可能想要 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 结构是正确的)。