【问题标题】:python check html validpython检查html是否有效
【发布时间】:2011-04-07 16:24:53
【问题描述】:

如何使用 Python 检查 HTML 代码的有效性?

我需要封闭标签检查和标签参数中的大括号。例如 |a href="xxx'| 和其他可能的验证,我可以使用哪些库?

【问题讨论】:

    标签: python html


    【解决方案1】:

    嗯,这不正是您要寻找的,但是为了验证我工作的网站的 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
    

    【讨论】:

    【解决方案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
    

    【讨论】:

    • 这似乎没有捕捉到以下无效的 HTML:html5parser.parseFragment('&lt;span&gt;&lt;div&gt;&lt;/div&gt;&lt;/span&gt;')
    猜你喜欢
    • 2012-04-19
    • 2014-02-09
    • 2011-05-05
    • 2012-07-21
    • 1970-01-01
    • 2013-06-24
    • 2015-04-11
    • 2019-09-18
    • 2015-11-26
    相关资源
    最近更新 更多