如何使用python检测字符串是否包含html代码?
如何检测字符串是否包含html(可以是html4、html5,只是文本中html的一部分)?我不需要HTML的版本,而是如果字符串只是文本或它包含HTML。文本通常是多行的,也有空行 更新: 输入示例: html:如何使用python检测字符串是否包含html代码?,python,html,parsing,detect,Python,Html,Parsing,Detect,如何检测字符串是否包含html(可以是html4、html5,只是文本中html的一部分)?我不需要HTML的版本,而是如果字符串只是文本或它包含HTML。文本通常是多行的,也有空行 更新: 输入示例: html: 我是title 你好,世界 非html: <ht fldf d>< <html><head> head <body></body> html < 头部html 检查结束标记。我相信这是最简单、最健壮的 "</
我是title
你好,世界
非html:
<ht fldf d><
<html><head> head <body></body> html
<
头部html
检查结束标记。我相信这是最简单、最健壮的
"</html>" in possibly_html
html中的“”
如果有一个结束html标记,那么它看起来像html,否则就不那么像了。我想到的一种方法是将开始标记和结束标记相交,通过尝试将文本解析为html并将该集合与已知的可接受html元素集相交来找到 示例:
#!/usr/bin/env python
from __future__ import print_function
from HTMLParser import HTMLParser
from html5lib.sanitizer import HTMLSanitizerMixin
class TestHTMLParser(HTMLParser):
def __init__(self, *args, **kwargs):
HTMLParser.__init__(self, *args, **kwargs)
self.elements = set()
def handle_starttag(self, tag, attrs):
self.elements.add(tag)
def handle_endtag(self, tag):
self.elements.add(tag)
def is_html(text):
elements = set(HTMLSanitizerMixin.acceptable_elements)
parser = TestHTMLParser()
parser.feed(text)
return True if parser.elements.intersection(elements) else False
print(is_html("foo bar"))
print(is_html("<p>Hello World!</p>"))
print(is_html("<html><head><title>Title</title></head><body><p>Hello!</p></body></html>")) # noqa
$ python foo.py
False
True
True
这适用于包含HTML元素子集的部分文本
NB:这使用了,因此它可能不一定适用于其他文档类型,但该技术可以很容易地进行调整。您可以使用HTML解析器,如。请注意,它确实尽了最大努力解析HTML,即使是已损坏的HTML,也可能非常宽松,具体取决于:
或者,您可以使用: 导入lxml.html >>>html='你好,世界'
>>>non_html=“在上一篇文章的基础上展开,我会做一些类似的事情,快速简单:
import sys, os
if os.path.exists("file.html"):
checkfile=open("file.html", mode="r", encoding="utf-8")
ishtml = False
for line in checkfile:
line=line.strip()
if line == "</html>"
ishtml = True
if ishtml:
print("This is an html file")
else:
print("This is not an html file")
导入系统,操作系统
如果os.path.exists(“file.html”):
checkfile=open(“file.html”,mode=“r”,encoding=“utf-8”)
ishtml=False
对于检查文件中的行:
line=line.strip()
如果行==“”
ishtml=True
如果是ishtml:
打印(“这是一个html文件”)
其他:
打印(“这不是html文件”)
这是一个很好的答案,假设输入是一个完整的HTML页面(其中包含
。它不适用于部分HTML(如某些单词)。此方法可以扩展为搜索任何html结尾标记,如b。正则表达式可能会使搜索速度更快,但基本原理保持不变。由于您不知道文本中可能存在哪些html标记,此技术将无法很好地工作:/它基本上与您的解决方案相同--只是使用不同的库和se已知元素的交叉点:PI在html5lib中再也找不到HTMLSanitizerMixin
。关于non-html=“head-html”
bool(BeautifulSoup(non-u-html,“html.parser”).find()=>True
?它不是html代码片段,即使non-u-html=“head-html-dkslfjglangaiowmgiowe”
也会通过测试:(@static-well,这将是True
,因为beautifulsou
尽最大努力解析html并保持宽容。它会将其转换为头html
。很好,它通过了许多有问题的案例,但看起来它通过了太多:非html=”@静态是的,在这种情况下,它认为fldf
和d
是属性,ht
标记只是没有关闭。很好的例子,谢谢:)关于部分和非样式html(即不是整行)(好的,这里可以使用“contains”而不是“==”)你是对的,我没有想到,在这种情况下,我可能会修改if line==“”:到if“”,在line:为什么你需要知道?你打算做什么不同的事情?只是检测字符串是否包含html,然后删除字符串或将其打印出来
>>> from bs4 import BeautifulSoup
>>> html = """<html>
... <head><title>I'm title</title></head>
... </html>"""
>>> non_html = "This is not an html"
>>> bool(BeautifulSoup(html, "html.parser").find())
True
>>> bool(BeautifulSoup(non_html, "html.parser").find())
False
>>> html = "Hello, <b>world</b>"
>>> bool(BeautifulSoup(html, "html.parser").find())
True
>>> import lxml.html
>>> html = 'Hello, <b>world</b>'
>>> non_html = "<ht fldf d><"
>>> lxml.html.fromstring(html).find('.//*') is not None
True
>>> lxml.html.fromstring(non_html).find('.//*') is not None
False
import sys, os
if os.path.exists("file.html"):
checkfile=open("file.html", mode="r", encoding="utf-8")
ishtml = False
for line in checkfile:
line=line.strip()
if line == "</html>"
ishtml = True
if ishtml:
print("This is an html file")
else:
print("This is not an html file")