HTML indenter written in Python

2024-06-14 09:05:51 发布

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

我正在寻找一个免费(如在自由)HTML压头(或重压头)编写的Python(模块或命令行)。我不需要用白名单过滤HTML。我只想缩进(或重新缩进)HTML源代码,使其更具可读性。例如,假设我有以下代码:

<ul><li>Item</li><li>Item
</li></ul>

输出可以是:

^{pr2}$

注意:我要找的不是非Python软件的接口(例如Tidy,用C编写),而是一个100%Python脚本。

非常感谢。在


Tags: 模块代码命令行脚本软件源代码htmlli
3条回答

您可以使用内置模块xml.dom.minidomtoprettyxml函数:

>>> from xml.dom import minidom
>>> x = minidom.parseString("<ul><li>Item</li><li>Item\n</li></ul>")
>>> print x.toprettyxml()
<?xml version="1.0" ?>
<ul>
    <li>
        Item
    </li>
    <li>
        Item
    </li>
</ul>

使用BeautifulSoup

有十几种方法可以使用BeautifulSoup模块和它的美化功能。这里有一些例子可以帮助你开始。在

从命令行

$ python -m BeautifulSoup < somefile.html > prettyfile.html

VIM内(手动)

如果您不想,您不必将文件写回磁盘,但是我包含了一个步骤,它将获得与命令行示例相同的效果。在

^{pr2}$

在VIM中(定义键映射)

在~/.vimrc中定义:

nmap =h !python -m BeautifulSoup < %<CR>

然后,当你在vim中打开一个文件,它需要美化

$vi somefile.html
=h
:w prettyfile.html

再次,保存美化是可选的。在

Python壳

$ python
>>> from BeautifulSoup import BeautifulSoup as parse_html_string
>>> from os import path
>>> uglyfile = path.abspath('somefile.html')
>>> path.isfile(uglyfile)
True
>>> prettyfile = path.abspath(path.join('.', 'prettyfile.html'))
>>> path.exists(prettyfile)
>>> doc = None
>>> with open(uglyfile, 'r') as infile, open(prettyfile, 'w') as outfile:
...     # Assuming very simple case
...     htmldocstr = infile.read()
...     doc = parse_html_string(htmldocstr)
...     outfile.write(doc.prettify())

# That's it; you can manually manipulate the dom too though
>>> scripts = doc.findAll('script')
>>> meta = doc.findAll('meta')
>>> print doc.prettify()
[imagine beautiful html here]

>>> import jsbeautifier
>>> print jsbeautifier.beautify(script.string)
[imagine beautiful script here]
>>> 

beauthoulsoup有一个名为prettify的函数,它可以完成此操作。 See this question

相关问题 更多 >