문제

문서가 특정 버전의 HTML(가급적으로 지정할 수 있음)을 따르는지 확인하는 가장 좋은 방법은 무엇입니까?네이티브 Python 앱을 제외하고 웹 기반 유효성 검사기에서와 같이 오류가 발생하는 위치를 알고 싶습니다.

도움이 되었습니까?

해결책

XHTML은 쉽습니다. 사용하세요 lxml.

HTML은 전통적으로 HTML 군중 사이에서 유효성 검사에 그다지 관심이 없었기 때문에 더 어렵습니다(유효성 검사기를 통해 StackOverflow 자체를 실행합니다).가장 쉬운 해결책은 다음과 같은 외부 응용 프로그램을 실행하는 것입니다. nsgmls 또는 오픈제이드, 출력을 구문 분석합니다.

다른 팁

PyTidyLib HTML Tidy를 위한 멋진 Python 바인딩입니다.그들의 예:

from tidylib import tidy_document
document, errors = tidy_document('''<p>f&otilde;o <img src="bar.jpg">''',
    options={'numeric-entities':1})
print document
print errors

게다가 둘 다 호환 가능 레거시 HTML 깔끔한 그리고 새로운 깔끔한-html5.

내 생각에 W3C 유효성 검사 서비스를 호출하는 가장 우아한 방법은 다음과 같습니다.

http://validator.w3.org/

프로그래밍 방식으로.서비스가 비표준 HTTP 헤더 매개변수를 반환하기 때문에 결과를 얻기 위해 결과를 화면 긁을 필요가 없다는 것을 아는 사람은 거의 없습니다.

X-W3C-Validator-Recursion: 1
X-W3C-Validator-Status: Invalid (or Valid)
X-W3C-Validator-Errors: 6
X-W3C-Validator-Warnings: 0

유효성과 오류 및 경고 수를 표시합니다.

예를 들어, 명령줄

curl -I "http://validator.w3.org/check?uri=http%3A%2F%2Fwww.stalsoft.com"

보고

HTTP/1.1 200 OK
Date: Wed, 09 May 2012 15:23:58 GMT
Server: Apache/2.2.9 (Debian) mod_python/3.3.1 Python/2.5.2
Content-Language: en
X-W3C-Validator-Recursion: 1
X-W3C-Validator-Status: Invalid
X-W3C-Validator-Errors: 6
X-W3C-Validator-Warnings: 0
Content-Type: text/html; charset=UTF-8
Vary: Accept-Encoding
Connection: close

따라서 W3C 유효성 검사 서비스를 우아하게 호출하고 HTTP 헤더에서 결과를 추출할 수 있습니다.

# Programmatic XHTML Validations in Python
# Martin Hepp and Alex Stolz
# mhepp@computer.org / alex.stolz@ebusiness-unibw.org

import urllib
import urllib2

URL = "http://validator.w3.org/check?uri=%s"
SITE_URL = "http://www.heppnetz.de"

# pattern for HEAD request taken from 
# http://stackoverflow.com/questions/4421170/python-head-request-with-urllib2

request = urllib2.Request(URL % urllib.quote(SITE_URL))
request.get_method = lambda : 'HEAD'
response = urllib2.urlopen(request)

valid = response.info().getheader('X-W3C-Validator-Status')
if valid == "Valid":
    valid = True
else:
    valid = False
errors = int(response.info().getheader('X-W3C-Validator-Errors'))
warnings = int(response.info().getheader('X-W3C-Validator-Warnings'))

print "Valid markup: %s (Errors: %i, Warnings: %i) " % (valid, errors, warnings)

HTML 유효성 검사기를 로컬로 설치하고 유효성 검사를 요청하는 클라이언트를 생성하기로 결정할 수 있습니다.

여기에서는 txt 파일의 URL 목록을 확인하는 프로그램을 만들었습니다.유효성 검사 상태를 얻기 위해 HEAD를 확인하고 있었지만 GET을 수행하면 전체 결과를 얻을 수 있습니다.유효성 검사기의 API를 보면 다양한 옵션이 있습니다.

import httplib2
import time

h = httplib2.Http(".cache")

f = open("urllistfile.txt", "r")
urllist = f.readlines()
f.close()

for url in urllist:
   # wait 10 seconds before the next request - be nice with the validator
   time.sleep(10)
   resp= {}
   url = url.strip()
   urlrequest = "http://qa-dev.w3.org/wmvs/HEAD/check?doctype=HTML5&uri="+url
   try:
      resp, content = h.request(urlrequest, "HEAD")
      if resp['x-w3c-validator-status'] == "Abort":
         print url, "FAIL"
      else:
         print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings']
   except:
      pass

tidylib을 사용해 보세요.elementtidy 모듈(HTML 문서에서 요소 트리를 빌드함)의 일부로 매우 기본적인 바인딩을 얻을 수 있습니다. http://effbot.org/downloads/#elementtidy

>>> import _elementtidy
>>> xhtml, log = _elementtidy.fixup("<html></html>")
>>> print log
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 7 - Warning: discarding unexpected </html>
line 1 column 14 - Warning: inserting missing 'title' element

로그를 구문 분석하면 필요한 거의 모든 것을 얻을 수 있습니다.

내 생각에는 HTML 정리 당신이 원하는 것을 할 것입니다.이에 대한 Python 바인딩이 있습니다.

내 경우에는 Python W3C/HTML 유효성 검사 패키지가 작동하지 않았습니다. pip search w3c (2016년 9월 기준).

나는 이것을 해결했다

$ pip install requests

$ python
Python 2.7.12 (default, Jun 29 2016, 12:46:54)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> r = requests.post('https://validator.w3.org/nu/', 
...                    data=file('index.html', 'rb').read(), 
...                    params={'out': 'json'}, 
...                    headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', 
...                    'Content-Type': 'text/html; charset=UTF-8'})

>>> r.text
>>> u'{"messages":[{"type":"info", ...

>>> r.json()
>>> {u'messages': [{u'lastColumn': 59, ...

여기에 더 많은 문서가 있습니다 파이썬 요청, W3C 유효성 검사기 API

이것은 lxml의 HTMLParser를 기반으로 하는 매우 기본적인 HTML 유효성 검사기입니다.인터넷 연결이 필요하지 않습니다.

_html_parser = None
def validate_html(html):
    global _html_parser
    from lxml import etree
    from StringIO import StringIO
    if not _html_parser:
        _html_parser = etree.HTMLParser(recover = False)
    return etree.parse(StringIO(html), _html_parser)

이는 닫는 태그를 확인하지 않으므로 예를 들어 다음이 통과됩니다.

validate_html("<a href='example.com'>foo</a>")

그러나 다음은 그렇지 않습니다.

validate_html("<a href='example.com'>foo</a")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top