python爬虫之xpath

一. python使用xpath

使用时先安装 lxml 包

pip install lxml

二. xpath简介

XPath,全称 XML Path Language,即 XML 路径语言,它是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。

  1. XPath 使用路径表达式在 XML 文档中进行导航
  2. XPath 包含一个标准函数库
  3. XPath 是 XSLT 中的主要元素
  4. XPath 是一个 W3C 标准

三. xpath语法

在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。树的根被称为文档节点或者根节点。

下面列出了最常用的表达式
image.png

通配符:
image.png

四. 实例

xml文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>

简单的查找
image.png

谓语 & 查找特定的节点
image.png

通配符举例
image.png

选取若干路径
image.png

五. 常用函数

5.1 starts-with() 获取以xxx开头的元素

xpath(‘//div[stars-with(@class,”test”)]’)

7.2 ends_with() 以xxx结尾

xpath("//input[ends-with(@id,'fuck')]")

7.3 contains() 获取包含xxx的元素

xpath(‘//div[contains(@id,”test”)]’)

7.4 and 并且 同时

xpath("//input[@type='submit' and @name='fuck']")

7.5 or 或者

xpath("//input[@type='submit' or @name='fuck']")

7.6 not 非

xpath("//input[@type='submit' and not(contains(@name,'fuck'))]")

7.7 text()

xpath(‘//div[contains(text(),”test”)]’)
xpath(‘//div[@id=”“test]/text()’)

参考:

  1. https://www.bilibili.com/video/BV1wa41197X9
  2. https://blog.csdn.net/xiaoweite1/article/details/104433926/
  3. https://blog.csdn.net/weixin_38819889/article/details/103233148
  4. https://www.cnblogs.com/mxjhaima/p/13775844.html
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值