lxml是一个HTML/XML的解析库,主要功能是如何解析和提取HTML/XML数据

lxml和正则一样,是用c实现的,我们可以用XPath语法,来快速的定位特定元素以及节点信息。需要用到pip。

使用:

1、解析一段html的字符串

from lxml import etree

text="""

# 一段html代码
"""

htmlElement=etree.HTML(text)
print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8'))

使用etree.HTML()

不需要解析器

2、解析一个html代码的文件

htmlElement=etree.parse("xxx.html")
print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8'))

使用etree.parse("xxx.html")

但是这个方法不能处理一些不规范的标签

所以要加一行解析器:parser=etree.HTMLParser(encoding='utf-8')

from lxml import etree



parser=etree.HTMLParser(encoding='utf-8')
htmlElement=etree.parse("lagou.html",parser=parser)

print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8'))

结果:

python爬虫(十三) lxml模块

 

相关文章:

  • 2021-07-30
  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2021-05-23
  • 2022-01-25
  • 2022-12-23
  • 2021-10-09
猜你喜欢
  • 2021-04-05
  • 2021-06-09
  • 2022-12-23
  • 2022-01-12
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案