XPath 即 XML 路径语言(XML Path Language),它是一种用来确定 xml 文档中某部分位置的语言。
xml 文档( html 属于 xml )是由一系列节点构成的树,例如:
Hello Python
Click here
xml 文档的节点有多种类型,其中最常用的有以下几种:
- 根节点 整个文档树的根。
- 元素节点 html、body、div、p、a。
- 属性节点 href。
- 文本节点 Hello Python、Click here。
节点间的关系有以下几种:
- 父子 body 是 html 的子节点,p 和 a 是 div 的子节点,反过来 div 是 p 和 a 的父节点。
- 兄弟 p 和 a 为兄弟节点。
- 祖先/后裔 body、div、p、a 都是 html 的后裔节点;反过来 html 是 body、div、p、a 的祖先节点。
01 基础语法
以下表格列出了 XPath 常用的基本语法。
![807a0322e39ef12b27cc78ded76efd6e.png](https://img-blog.csdnimg.cn/img_convert/807a0322e39ef12b27cc78ded76efd6e.png)
接下来,我们通过一些例子展示 XPath 的使用。
首先创建一个用于演示的 html 文档,并用其构造一个 HTMLResponse 对象:
>>> from scrapy.selector import Selector>>> from scrapy.http import HtmlResponse>>> body = '''... ... ... ... Hello Scrapy... ... ...
... Name:Image 1
... Name:Image 2
... Name:Image 3
... Name:Image 4
... Name:Image 5
...
... ... ... '''>>> >>> response = HtmlResponse(url="http://www.example.com",body=body,encoding='utf8')
![7ff09cd6682f5fcef610c48c6d756067.png](https://img-blog.csdnimg.cn/img_convert/7ff09cd6682f5fcef610c48c6d756067.png)
- /: 描述一个从根开始的绝对路径。
>>> response.xpath('/html')[]>>> response.xpath('/html/head')[]