当前位置:   article > 正文

使用lxml解析HTML代码_lxml.etree.htmlparser()

lxml.etree.htmlparser()

1. 解析html字符串。使用“lxml.etree.HTML( )”进行解析。etree.tostring( )方法可以将htmlelement元素转化成字符串,可以正常打印出来。示例代码如下:

  1. # --coding:utf-8-- #
  2. from lxml import etree
  3. text = """
  4. """
  5. htmlelement = etree.HTML(text)
  6. print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")

2. 解析html文件。使用“lxml.etree.parse( )”进行解析,该方法默认使用的是“XML”解析器,所以如果碰到不规范的html文件时就会解析错误,报错代码如下:

  1. # --coding:utf-8-- #
  2. from lxml import etree
  3. htmlelement = etree.parse("C:\\Users\\Administrator\\Desktop\\baidu.html")
  4. print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")
  1. D:\Python3\python27\python.exe
  2. lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 3 and head, line 3, column 87
  3. Process finished with exit code 1

这时就要自己创建html解析器,增加参数“parser”,示例代码如下:

  1. # --coding:utf-8-- #
  2. from lxml import etree
  3. parser = etree.HTMLParser(encoding="utf-8")
  4. htmlelement = etree.parse("C:\\Users\\Administrator\\Desktop\\baidu.html", parser=parser)
  5. print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读