相关疑难解决方法(0)

如何使用缩进将HTML打印到文件中

我正在使用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>

html python lxml pretty-print

59
推荐指数
5
解决办法
6万
查看次数

xml.parsers.expat.ExpatError:格式不正确(令牌无效)

当我使用 xmltodict 加载下面的 xml 文件时,出现错误: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1

这是我的文件:

<?xml version="1.0" encoding="utf-8"?>
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
Run Code Online (Sandbox Code Playgroud)

来源:

import xmltodict
with open('fileTEST.xml') as fd:
   xmltodict.parse(fd.read())
Run Code Online (Sandbox Code Playgroud)

我在 Windows 10 上,使用 Python 3.6 和 xmltodict 0.11.0

如果我使用 ElementTree 它可以工作

tree = ET.ElementTree(file='fileTEST.xml')
    for elem in tree.iter():
            print(elem.tag, elem.attrib)

mydocument {'has': 'an attribute'}
and {}
many {}
many {}
plus {'a': 'complex'}
Run Code Online (Sandbox Code Playgroud)

注意:我可能遇到了换行问题。
注2:我在两个不同的文件上使用了Beyond Compare。
它在 UTF-8 …

python-3.x windows-10

14
推荐指数
4
解决办法
2万
查看次数

标签 统计

html ×1

lxml ×1

pretty-print ×1

python ×1

python-3.x ×1

windows-10 ×1