python - 使用 Python 编辑和创建 HTML 文件

标签 python html python-3.x python-import

我目前正在完成一项使用 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/

相关文章:

python - Bottle.py 的动态路由

php - 从 HTML 中删除空格

javascript - 使用 Javascript 将图像保存在 HTML 页面中

python - 没有名为 'requests_toolbelt' 的模块

python - Django 和 Pymongo - 获取多个输入并更新所有对象中的单个字段

python - Spacy NER实体位置

javascript - 使用 x-editable 切换 select2

python-3.x - ansible 剧本错误为 : ModuleNotFoundError: No module named 'azure.mgmt.monitor.version' although the module is installed

python - 在 Python 3 中使用套接字获取 400 Bad Request 错误

python - Cartopy 混合投影和重叠绘制图像数据