爬虫之xpath和lxml模块

爬虫之xpath和lxml模块

xpath介绍

基本介绍

  • XPath(XML Path Language)是一种XML的查询语言,他能在XML树状结构中寻找节点。XPath 用于在 XML 文档中通过元素和属性进行导航

  • xml是一种标记语法的文本格式,xpath可以方便的定位xml中的元素和其中的属性值。lxml是python中的一个包,这个包中包含了将html文本转成xml对象,和对对象执行xpath的功能

节点介绍

首先我们下举一个文档例子来了解节点是什么:

xml_content = '''
<bookstore>
<book>
    <title lang='eng'>Harry Potter</title>
    <author>K.Rowing</author>
    <year>2005</year>
    <price>29<price>
</book>
</bookstore>
'''

在上面的文档中有很多节点:

  • 文档节点
  • <title> 元素节点
  • lang=‘en’ 属性节点

其中:

  • book元素节点是title、auther、year、price的父节点
  • title、auther、year、price是兄弟节点
  • title、auther、year、price是book的子节点
  • book和bookstore是title、auther、year、price的先辈节点

xpath的使用

工具的安装

首先,使用xpath我们要在浏览器上安装xpath插件

  • chrome浏览器安装XPath Helper
  • Firefox浏览器安装XPath Checker

安装插件的参考网站:

https://blog.csdn.net/qq_31082427/article/details/84987723

xpath的使用表达式如下:

image.png

image.png

image.png

xpath的模块

  • 在python中,xpath需要安装lxml模块才能使用

  • lxml 是 一个HTML/XML的解析器,主要的功能是如何解析和提取HTML/XML数据利用etree.HTML,将字符串转化为Element对象

  • lxml python 官方文档:http://lxml.de/index.html

  • 模块安装 pip 安装:pip install lxml

  • lxml 可以⾃动修正 html 代码

xpath使用用例:

xml_content = '''
<bookstore>
<book>
    <title lang='eng'>Harry Potter</title>
    <author>K.Rowing</author>
    <year>2005</year>
    <price>29<price>
</book>
</bookstore>
'''

上面是一个html文档的一部分,接下来通过对它的操作来介绍xpath:

#首先导入模块
from lxml import etrre

#测试用例
xml_content = '''
<bookstore>
<book>
    <title lang='eng'><a href="https://HarryPotter.com">Harry Potter</a></title>
    <author>K.Rowing</author>
    <year>2005</year>
    <price>29<price>
</book>
</bookstore>
'''

#使用etrre.HTML()将html文档转换为element对象
htmlElement = etree.HTMl(xml_content)

#通过element对象将对象转换为字符串或二进制类型
#通过xpath()来定位节点
title = htmlElement.xpath('book/title[@lang='eng']/text()')
href = htmlElement.xpath('book/title/a/@href')
print(title)
print(href)
#输出结果为:
#Harry Potter
#https://HarryPotter.com
 htmlElement.xpath('book/title/a/@href')
print(title)
print(href)
#输出结果为:
#Harry Potter
#https://HarryPotter.com
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值