【发布时间】:2011-04-07 16:24:53
【问题描述】:
如何使用 Python 检查 HTML 代码的有效性?
我需要封闭标签检查和标签参数中的大括号。例如 |a href="xxx'| 和其他可能的验证,我可以使用哪些库?
【问题讨论】:
如何使用 Python 检查 HTML 代码的有效性?
我需要封闭标签检查和标签参数中的大括号。例如 |a href="xxx'| 和其他可能的验证,我可以使用哪些库?
【问题讨论】:
嗯,这不正是您要寻找的,但是为了验证我工作的网站的 HTML,我要求 W3C 验证器为我检查它,然后我只是截取输出以获取基本的是/否结果。请注意,网络上有多种验证服务可供选择,但 W3C 对我来说已经足够好了。
#!/usr/bin/python2.6
import re
import urllib
import urllib2
def validate(URL):
validatorURL = "http://validator.w3.org/check?uri=" + \
urllib.quote_plus(URL)
opener = urllib2.urlopen(validatorURL)
output = opener.read()
opener.close()
if re.search("This document was successfully checked as".replace(
" ", r"\s+"), output):
print " VALID: ", URL
else:
print "INVALID: ", URL
【讨论】:
html5lib 模块可用于执行基本的 HTML 验证:
>>> import html5lib
>>> html5parser = html5lib.HTMLParser(strict=True)
>>> html5parser.parse('<html></html>')
Traceback (most recent call last):
...
html5lib.html5parser.ParseError: Unexpected start tag (html). Expected DOCTYPE.
>>> 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 option
【讨论】:
html5parser.parseFragment('<span><div></div></span>')。