如何在Python2中脱机验证xHtml1.1文档

时间:2018-07-08 21:08:28

标签: python python-2.7 xhtml lxml w3c-validation

我需要设置一个测试方法,以验证作为Python字符串提供的标记是否为有效的xHtml1.1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

由于它将在内部CI上运行,因此它必须能够处理而不将内容发送到任何外部服务(我不希望使用https://validator.w3.org/之类的在线验证器,但会得到类似的结果)。

我发现的是https://lxml.de/validation.html#id1,它看起来很有希望。问题是我一直在获取有效的DTD。

from lxml.etree import DTD
dtd = DTD(external_id = "-//W3C//DTD XHTML 1.1//EN")

这对我不起作用:(

---------------------------------------------------------------------------
DTDParseError                             Traceback (most recent call last)
<ipython-input-13-c6bf8522a141> in <module>()
----> 1 dtd = DTD(external_id = "-//W3C//DTD XHTML 1.1//EN")

/tmp/tmp.dWRxTnmLqz/venv/lib/python2.7/site-packages/lxml/etree.so in lxml.etree.DTD.__init__()

DTDParseError: error parsing DTD

1 个答案:

答案 0 :(得分:0)

我发现w3c-sgml-lib软件包提供了缺少的DTD,因此在安装此DTDParseError之后不再出现:

 sudo apt install w3c-sgml-lib libxml2

目前,我正在使用Python2代码进行 xHtml1.1 验证,类似于以下代码:

 #!/usr/bin/env python2
 # vim: set fileencoding=utf-8 :
 #
 # This is an example for https://stackoverflow.com/q/51236003/388968
 #
 # Copyright 2018 (c) Sebastian Sawicki (0x52fb0d10)
 #  OPENPGP4FPR:5691BED8E6CA579830842DD85CB361E552FB0D10
 #
 # Licence: https://creativecommons.org/licenses/by/4.0/
 #

 from lxml.etree import DTD
 from lxml.etree import fromstring

 from six import string_types

 def isValidXHtml11(s):
  return isinstance(s, string_types) and
   s.startswith('<?xml version="1.0" encoding="UTF-8"?>\n' +
   '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ' +
   '"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n') and
   DTD(external_id = '-//W3C//DTD XHTML 1.1//EN').validate(
    fromstring(response.body)
   )

...无论如何,这是开放的任何建议或改进。

相关问题