XPath入门:XPath的介绍与使用方法

一、xpath介绍

  • XPath 是一门在 XML 文档中查找信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航。
  • XPath 使用路径表达式在 XML 文档中进行导航。
  • XPath 包含一个标准函数库
  • XPath 是 XSLT 中的主要元素
  • XPath 是一个 W3C 标准

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

二、xpath语法

表达式描述
nodename选取此节点的所有子节点。
/从根节点选取。
//从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
.选取当前节点。
选取当前节点的父节点。
@选取属性。

例子
以下面这个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>
  • xml.xpath(“bookstore”) 表示选取 bookstore 元素的所有子节点
  • xml.xpath(“/bookstore”) 表示选取根元素 bookstore。
  • xml.xpath(“bookstore/book”) 选取属于 bookstore 的子元素的所有 book 元素。
  • xml.xpath(“//book”) 选取所有 book 子元素,而不管它们在文档中的位置。
  • xml.xpath(“bookstore//book”) 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
  • xml.xpath(“//@lang”) 选取名为 lang 的所有属性。

谓语

路径表达式结果
/bookstore/book[1]选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()]选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1]选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()❤️]选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang]选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=’eng’]选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00]选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

选取未知节点

通配符描述
*匹配任何元素节点。
@*匹配任何属性节点。
node()匹配任何类型的节点。

例子:

路径表达式结果
/bookstore/*选取 bookstore 元素的所有子元素。
//*选取文档中的所有元素。
//title[@*]选取所有带有属性的 title 元素。

选取若干路径
通过在路径表达式中使用“|”运算符,您可以选取若干个路径。

  • //book/title | //book/price 选取 book 元素的所有 title 和 price 元素。
  • //title | //price 选取文档中的所有 title 和 price 元素。
  • /bookstore/book/title | //price 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素。

三、轴

轴可定义相对于当前节点的节点集。

轴名称结果
ancestor选取当前节点的所有先辈(父、祖父等)。
ancestor-or-self选取当前节点的所有先辈(父、祖父等)以及当前节点本身。
attribute选取当前节点的所有属性。
child选取当前节点的所有子元素。
descendant选取当前节点的所有后代元素(子、孙等)。
descendant-or-self选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following选取文档中当前节点的结束标签之后的所有节点。
namespace选取当前节点的所有命名空间节点。
parent选取当前节点的父节点。
preceding选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling选取当前节点之前的所有同级节点。
self选取当前节点。

步的语法:
轴名称:节点测试[谓语]
例子:

例子结果
child:book选取所有属于当前节点的子元素的 book 节点。
attribute:lang选取当前节点的 lang 属性。
child:*选取当前节点的所有子元素。
attribute:*选取当前节点的所有属性。
child::text()选取当前节点的所有文本子节点。
child::node()选取当前节点的所有子节点。
descendant::book选取当前节点的所有 book 后代。
ancestor::book选择当前节点的所有 book 先辈。
ancestor-or-self::book选取当前节点的所有 book 先辈以及当前节点(如果此节点是 book 节点)
child:?/child::price选取当前节点的所有 price 孙节点。

四、一些函数

  1. starts-with函数
    获取以xxx开头的元素
    例子:xpath(‘//div[stars-with(@class,”test”)]’)
  2. contains函数
    获取包含xxx的元素
    例子:xpath(‘//div[contains(@id,”test”)]’)
  3. and
    与的关系
    例子:xpath(‘//div[contains(@id,”test”) and contains(@id,”title”)]’)
  4. text()函数
    例子1:xpath(‘//div[contains(text(),”test”)]’)
    例子2:xpath(‘//div[@id=”“test]/text()’)

五、一个lxml的xpath示例

#coding=utf-8

from lxml import etree

html = '''

<html>
  <head>
    <meta name="content-type" content="text/html; charset=utf-8" />
    <title>友情链接查询 - 站长工具</title>
    <!-- uRj0Ak8VLEPhjWhg3m9z4EjXJwc -->
    <meta name="Keywords" content="友情链接查询" />
    <meta name="Description" content="友情链接查询" />

  </head>
  <body>
    <h1 class="heading">Top News</h1>
    <p style="font-size: 200%">World News only on this page</p>
    Ah, and here's some more text, by the way.
    <p>... and this is a parsed fragment ...</p>

    <a href="http://www.cydf.org.cn/" rel="nofollow" target="_blank">青少年发展基金会</a> 
    <a href="http://www.4399.com/flash/32979.htm" target="_blank">洛克王国</a> 
    <a href="http://www.4399.com/flash/35538.htm" target="_blank">奥拉星</a> 
    <a href="http://game.3533.com/game/" target="_blank">手机游戏</a>
    <a href="http://game.3533.com/tupian/" target="_blank">手机壁纸</a>
    <a href="http://www.4399.com/" target="_blank">4399小游戏</a> 
    <a href="http://www.91wan.com/" target="_blank">91wan游戏</a>

  </body>
</html>

'''
page = etree.HTML(html.lower().decode('utf-8'))
hrefs = page.xpath(u"//a")
for href in hrefs:
    print href.attrib

打印出的结果为:

{‘href’: ‘http://www.cydf.org.cn/‘, ‘target’: ‘_blank’, ‘rel’: ‘nofollow’}
{‘href’: ‘http://www.4399.com/flash/32979.htm‘, ‘target’: ‘_blank’}
{‘href’: ‘http://www.4399.com/flash/35538.htm‘, ‘target’: ‘_blank’}
{‘href’: ‘http://game.3533.com/game/‘, ‘target’: ‘_blank’}
{‘href’: ‘http://game.3533.com/tupian/‘, ‘target’: ‘_blank’}
{‘href’: ‘http://www.4399.com/‘, ‘target’: ‘_blank’}
{‘href’: ‘http://www.91wan.com/‘, ‘target’: ‘_blank’}

如果要获取标签a之间的内容,就可以用print href.text输出

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Python中使用XPath可以通过lxml库来实现。首先,你需要安装lxml库,可以通过在编辑器(如pycharm)控制台输入pip install lxml来安装。另外,你还需要安装requests库来获取网页源码数据,可以通过pip install requests来安装。\[2\]接下来,你可以使用etree.parse(filePath)方法将本地的HTML文档中的源码数据加载到etree对象中,也可以使用etree.HTML('page_text')方法将从互联网上获取的源码数据加载到该对象中。\[3\]然后,你可以使用xpath表达式来定位和提取所需的数据,例如使用/:表示从根节点开始定位,//:表示多个层级,//div\[@class='zhang'\]表示定位class属性为'zhang'的div标签,//div\[@class="zhang"\]/p\[3\]表示定位class属性为'zhang'的div标签下的第三个p标签。\[1\]如果你想获取标签中的文本内容,可以使用/text()获取标签中直系的文本内容,或者使用//text()获取标签中非直系的文本内容(所有的文本内容)。如果你想获取标签的属性,可以使用/@attrName来获取。希望这些信息对你有帮助。 #### 引用[.reference_title] - *1* *3* [Python爬虫xpath详解](https://blog.csdn.net/TreeShu321/article/details/122270055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python--爬虫--XPath入门](https://blog.csdn.net/qq_57663276/article/details/127129747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值