基于whatwg html规范的html解析器

html5lib的Python项目详细描述


用法

简单用法如下:

importhtml5libwithopen("mydocument.html","rb")asf:document=html5lib.parse(f)

或:

importhtml5libdocument=html5lib.parse("<p>Hello World!")

默认情况下, 文档 将是一个 xml.etree 元素实例。 只要可能,html5lib就会选择加速的元素树。 实现(即python 2.x上的 xml.etree.celementree

支持另外两种树类型: xml.dom.minidom lxml.etree 。要使用替代格式,请指定 树型建筑:

importhtml5libwithopen("mydocument.html","rb")asf:lxml_etree_document=html5lib.parse(f,treebuilder="lxml")

urllib2(python 2)一起使用时,http中的字符集应该是 按如下方式传递到html5lib:

fromcontextlibimportclosingfromurllib2importurlopenimporthtml5libwithclosing(urlopen("http://example.com/"))asf:document=html5lib.parse(f,transport_encoding=f.info().getparam("charset"))

当与 urllib.request(python 3)一起使用时,来自http的字符集 应该按如下方式传递到html5lib中:

fromurllib.requestimporturlopenimporthtml5libwithurlopen("http://example.com/")asf:document=html5lib.parse(f,transport_encoding=f.info().get_content_charset())

要对解析器有更多的控制,请显式地创建一个解析器对象。 例如,要使解析器在分析错误时引发异常,请使用:

importhtml5libwithopen("mydocument.html","rb")asf:parser=html5lib.HTMLParser(strict=True)document=parser.parse(f)

当显式实例化解析器对象时,传递一个treebuilder 类作为 关键字参数使用替代文档 格式:

importhtml5libparser=html5lib.HTMLParser(tree=html5lib.getTreeBuilder("dom"))minidom_document=parser.parse("<p>Hello World!")

有关更多文档,请访问https://html5lib.readthedocs.io/" rel="nofollow">https://html5lib.readthedocs.io/

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java检查整数是0还是检查变量是null更好?   java Android Kotlin(初学者)使用File(),并从ACTION\u GET\u内容返回Uri   java JavaFx在“内部场景”和根场景之间切换   spring将XMLBean配置转换为java配置   java JPA HIBERNATE映射列两次(embeddedID和POJO)   c#单态模式模型在什么情况下适用?   java请求。getRemoteUser在特定时间后返回null?   spring boot中PUT api控制器的java my单元测试用例失败   java在字符串中互换地解析和替换值   java Android JNI在应用程序中检测到错误:调用JNI GetMethodID时出现挂起异常   JavaSpringDataMongo:使用非简单键持久化映射   爪哇玻璃鱼连接被拒绝   java如何在用户注册时发送特定电子邮件id的自动回复?   Java列表:实例化时和之后的赋值之间的差异