python 检查 HTML 是否有效

2 投票
2 回答
5329 浏览
提问于 2025-04-16 03:39

我怎么用Python检查HTML代码的有效性呢?

我需要检查标签是否闭合,还有标签参数里的括号,比如像这个 |a href="xxx'| 这样的情况,以及其他可能的验证。我可以用哪些库来做到这些呢?

2 个回答

2

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
3

好吧,这个可能不是你想要的答案,但为了验证我正在做的网站的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

撰写回答