bco*_*not 59 html python lxml pretty-print
我正在使用lxml.html生成一些HTML.我想打印(带缩进)我的最终结果到一个html文件.我怎么做?
这是我迄今为止所尝试过的(我对Python和lxml相对较新):
import lxml.html as lh
from lxml.html import builder as E
sliderRoot=lh.Element("div", E.CLASS("scroll"), style="overflow-x: hidden; overflow-y: hidden;")
scrollContainer=lh.Element("div", E.CLASS("scrollContainer"), style="width: 4340px;")
sliderRoot.append(scrollContainer)
print lh.tostring(sliderRoot, pretty_print = True, method="html")
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在使用该pretty_print=True属性.我认为这会给缩进代码,但它并没有真正帮助.这是输出:
<div style="overflow-x: hidden; overflow-y: hidden;" class="scroll"><div style="width: 4340px;" class="scrollContainer"></div></div>
bco*_*not 82
我最终直接使用了BeautifulSoup.这是lxml.html.soupparser用于解析HTML的东西.
BeautifulSoup有一种美化方法,可以完全按照它的说法进行操作.它用适当的缩进和一切来美化HTML.
BeautifulSoup不会修复HTML,因此破坏的代码仍然存在.但在这种情况下,由于代码是由lxml生成的,因此HTML代码至少在语义上是正确的.
在我的问题中给出的例子中,我将不得不这样做:
from BeautifulSoup import BeautifulSoup as bs
root = lh.tostring(sliderRoot) #convert the generated HTML to a string
soup = bs(root) #make BeautifulSoup
prettyHTML = soup.prettify() #prettify the html
Run Code Online (Sandbox Code Playgroud)
Jay*_*oot 31
虽然我的回答现在可能没什么用,但是我将它放在这里作为未来任何人的参考.
lxml.html.tostring()事实上,尽管如此,并不能完全打印提供的HTML pretty_print=True.
然而,它的"兄弟姐妹" lxml.html- lxml.etree运作良好.
所以可以使用它如下:
from lxml import etree, html
document_root = html.fromstring("<html><body><h1>hello world</h1></body></html>")
print(etree.tostring(document_root, encoding='unicode', pretty_print=True))
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
<html>
<body>
<h1>hello world</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Ale*_*exG 16
如果将HTML存储为无格式字符串,则在变量中html_string,可以使用beautifulsoup4完成,如下所示:
from bs4 import BeautifulSoup
print(BeautifulSoup(html_string, 'html.parser').prettify())
Run Code Online (Sandbox Code Playgroud)
如果再添加一个依赖项不成问题,您可以使用html5print包。与其他解决方案相比,它的优势在于它还可以美化嵌入在 HTML 文档中的 CSS 和 Javascript 代码。
要安装它,请执行:
pip install html5print
Run Code Online (Sandbox Code Playgroud)
然后,您可以将其用作命令:
html5-print ugly.html -o pretty.html
Run Code Online (Sandbox Code Playgroud)
或作为 Python 代码:
from html5print import HTMLBeautifier
html = '<title>Page Title</title><p>Some text here</p>'
print(HTMLBeautifier.beautify(html, 4))
Run Code Online (Sandbox Code Playgroud)
我尝试了 BeautifulSoupprettify和 html5print 的HTMLBeautifier解决方案,但由于我使用yattag来生成 HTML,因此使用它的indent函数似乎更合适,它可以产生很好的缩进输出。
from yattag import indent
rawhtml = "String with some HTML code..."
result = indent(
rawhtml,
indentation = ' ',
newline = '\r\n',
indent_text = True
)
print(result)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64009 次 |
| 最近记录: |