使用Python编辑和创建HTML文件

2024-04-16 17:10:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。我目前正在做一个使用python创建HTML文件的任务。我知道如何将HTML文件读入python,然后编辑并保存它。

table_file = open('abhi.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()

上面这段代码的问题是它只是替换了整个HTML文件并将字符串放入write()中。如何编辑文件,同时保持其内容完整。我是说,写一些类似的东西,但是在身体标签里面

<link rel="icon" type="image/png" href="img/tor.png">

我需要的链接,以自动之间打开和关闭身体标签。


Tags: 文件编辑pnghtmltablebody标签open
2条回答

你可能想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结构)。

您正在使用write(w)模式,该模式将删除现有文件(https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)。改用append(a)模式:

table_file = open('abhi.html', 'a')

相关问题 更多 >