2024-06-14 09:05:51 发布
网友
我正在寻找一个免费(如在自由)HTML压头(或重压头)编写的Python(模块或命令行)。我不需要用白名单过滤HTML。我只想缩进(或重新缩进)HTML源代码,使其更具可读性。例如,假设我有以下代码:
<ul><li>Item</li><li>Item </li></ul>
输出可以是:
注意:我要找的不是非Python软件的接口(例如Tidy,用C编写),而是一个100%Python脚本。
非常感谢。在
您可以使用内置模块xml.dom.minidom的toprettyxml函数:
xml.dom.minidom
toprettyxml
>>> 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模块和它的美化功能。这里有一些例子可以帮助你开始。在
$ python -m BeautifulSoup < somefile.html > prettyfile.html
如果您不想,您不必将文件写回磁盘,但是我包含了一个步骤,它将获得与命令行示例相同的效果。在
在~/.vimrc中定义:
nmap =h !python -m BeautifulSoup < %<CR>
然后,当你在vim中打开一个文件,它需要美化
$vi somefile.html =h :w prettyfile.html
再次,保存美化是可选的。在
$ 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
prettify
您可以使用内置模块
xml.dom.minidom
的toprettyxml
函数:使用BeautifulSoup
有十几种方法可以使用BeautifulSoup模块和它的美化功能。这里有一些例子可以帮助你开始。在
从命令行
VIM内(手动)
如果您不想,您不必将文件写回磁盘,但是我包含了一个步骤,它将获得与命令行示例相同的效果。在
^{pr2}$在VIM中(定义键映射)
在~/.vimrc中定义:
然后,当你在vim中打开一个文件,它需要美化
再次,保存美化是可选的。在
Python壳
beauthoulsoup有一个名为
prettify
的函数,它可以完成此操作。 See this question相关问题 更多 >
编程相关推荐