使用BeautifulSoup
有十几种方法可以使用BeautifulSoup模块和它的美化功能。这里有一些例子可以帮助你开始。在
从命令行$ python -m BeautifulSoup < somefile.html > prettyfile.html
VIM内(手动)
如果您不想,您不必将文件写回磁盘,但是我包含了一个步骤,它将获得与命令行示例相同的效果。在
^{pr2}$
在VIM中(定义键映射)
在~/.vimrc中定义:nmap =h !python -m BeautifulSoup < %
然后,当你在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]
>>>