我使用Python和html5lib来检查表单字段中输入的一些HTML代码是否有效。
我尝试了下面的代码来测试一个有效的片段,但是我得到了一个意外的错误(至少对我来说是这样):
>>> import html5lib
>>> from html5lib.filters import lint
>>> fragment = html5lib.parseFragment('<p><script>alert("Boo!")</script></p>')
>>> walker = html5lib.getTreeWalker('etree')
>>> [i for i in lint.Filter(walker(fragment))]
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/xyz/html5lib-1.0b3-py2.7.egg/html5lib/filters/lint.py", line 28, in __iter__
raise LintError(_("Tag name is not a string: %(tag)r") % {"tag": name})
LintError: Tag name is not a string: u'p'我做错什么了?
我的默认编码是utf-8
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'发布于 2015-05-01 18:00:54
lint过滤器不尝试验证HTML (嗯,是的,需要文档,非常…这是目前还没有1.0版本的很大一部分原因),它只是验证treewalker是否被遵守。但并不是因为它因为第172号问题而坏了。
html5lib并不试图提供任何验证器,因为实现一个HTML验证器需要做很多工作。
除了Validator.nu之外,我不知道有任何比较完整的验证器,尽管这是用Java编写的。然而,它提供了一个可能适合您的web API。
发布于 2020-03-27 12:33:10
“严格”解析模式可用于检测错误:
>>> import html5lib
>>> html5parser = html5lib.HTMLParser(strict=True)
>>> html5parser.parseFragment('<p>Lorem <a href="/foobar">ipsum</a>')
<Element 'DOCUMENT_FRAGMENT' at 0x7f1d4a58fd60>
>>> html5parser.parseFragment('<p>Lorem </a>ipsum<a href="/foobar">')
Traceback (most recent call last):
...
html5lib.html5parser.ParseError: Unexpected end tag (a). Ignored.
>>> html5parser.parseFragment('<p><form></form></p>')
Traceback (most recent call last):
...
html5lib.html5parser.ParseError: Unexpected end tag (p). Ignored.
>>> html5parser.parseFragment('<option value="example" />')
Traceback (most recent call last):
...
html5lib.html5parser.ParseError: Trailing solidus not allowed on element optionhttps://stackoverflow.com/questions/29567776
复制相似问题