使用Python编辑和创建HTML文件 [英] Edit and create HTML file using Python
问题描述
我对Python真的很陌生。目前正在使用Python创建一个HTML文件的工作。我已经有了用python读取HTML文件并编辑和保存的基本方法。
I am really new to Python. Currently working on an assignment for creating an HTML file using python. I have got the basic way of reading an HTML file in python and editing and saving the same.
table_file = open('abhi.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()
上面的问题是它只是编辑整个HTML文件,并将该命令写入。我的查询是关于我可以编辑文件,同时保持它的内容不变。我的意思是,写这样的东西,但在 body标签
The problem with the above piece is it's just editing whole HTML file and the putting the command under write. My query is regarding that can I edit the file and the same time keep it's content intact. I mean, writing something like this, but under body tags
<link rel="icon" type="image/png" href="img/tor.png">
要求您相应地引导。
推荐答案
您可能想阅读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>
这会产生
this produces
<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结构)。
(note: it has munched the whitespace, but gotten the html structure correct).
这篇关于使用Python编辑和创建HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!