我想验证 HTML 标记以确定它是否是有效的 HTML。
我尝试了以下代码。
def must_have_proper_htmltag(self,filename):
"""
:param filename:
:return:
"""
print(filename)
return bool(BeautifulSoup(filename, 'html.parser').find())
'''Beautiful soup is library function to pull HTML or XML
html.parser is for choosing html doc and find() for
checking occuranc'''
`htmltags='<html><head><title>Test</title></head>''<body><h1>Parse me!</h1>
</body></html>'
nohtmltag = '<html><head><title>Test</title></head>''<body><h1>Parse me!'
print('html checkers:-',qc.must_have_proper_htmltag(htmltag))
print('html checkers:-',qc.must_have_proper_htmltag(nohtmltag))
该函数检查是否有HTML标签。它不验证HTML标签是否正确。
如何验证 HTML 标记?我想要输出 HTML 标签一个是 True 另一个是 False
最佳答案
您可以使用 w3c 验证器对其进行验证
from py_w3c.validators.html.validator import HTMLValidator
def must_have_proper_htmltag(self,filename):
"""
:param filename:
:return:
"""
print(filename)
html_validator = HTMLValidator()
html_validator.validate_fragment(filename)
if not html_validator.errors:
'''Where there is no error it return empty list'''
return True
else:
return False
print('html checkers:-',qc.must_have_proper_htmltag('<!DOCTYPE html><html>
<head><title>Test</title></head>''<body><h1>Parse me!</h1></body></html>'))
关于python - Python 中的 HTML 标签验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47989711/