【问题标题】:Edit and create HTML file using Python使用 Python 编辑和创建 HTML 文件
【发布时间】:2016-05-23 04:00:55
【问题描述】:

我对 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">

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

【问题讨论】:

  • 我不知道我是否正确理解了你的分配范围,但我建议你看看 BeautifulSoup (crummy.com/software/BeautifulSoup)
  • 主要是因为使用您采用的方法,您可以将整个 html 放在单个文档字符串中,然后将其写入文件。没有任何关于它的程序化
  • 如果某个答案对您有帮助,您应该接受它作为解决方案。

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


【解决方案1】:

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

【讨论】:

  • 休:非常感谢您的快速回复。这真的很有帮助。
【解决方案2】:

您正在使用写入 (w) 模式,这将擦除现有文件 (https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)。改用追加 (a) 模式:

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

【讨论】:

  • 感谢您的回复。但是,如果 html 结构是这样的 html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;API documentation&lt;/title&gt; &lt;link rel="stylesheet" href="css/foundation.min.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; 我的意思是,这会起作用吗, 会自动添加到 标签之间吗??
  • 不,它将按照您添加它们的顺序附加。对了,&lt;link&gt;标签为什么要在&lt;body&gt;标签之间呢?
  • 我只是在问一个问题。我知道它应该在 head 标签下。那么请建议我如何创建一个条件循环以在 bodyhead 标签下添加命令,同时解析 html 文件然后保存它
  • 如果你想解析和修改一个现有的 HTML 文件,@HughBothwell 提供的答案中的 BeautifulSoup 库更合适。
猜你喜欢
  • 2015-10-24
  • 1970-01-01
  • 2013-03-28
  • 2022-06-27
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
相关资源
最近更新 更多