选取节点
XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。
下面列出了最有用的路径表达式:
表达式 | 描述 |
---|---|
nodename | 选取此节点的所有子节点。 |
/ | 从根节点选取。 |
// | 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。 |
. | 选取当前节点。 |
.. | 选取当前节点的父节点。 |
@ | 选取属性。 |
* | 选中所有元素子节点。 |
text() | 选中所有文本子节点。 |
[谓语] | 谓语用来查找某个特定的节点或者包含某个特定值得节点。 |
XPath常用示例
- /: 描述一个从根开始的绝对路径
>>>response.xpath('/html')
>>>response.xpath('/html/head')
- E1/E2: 选中E1子节点中的所有E2
>>>response.xpath('/html/body/div/a')
- //E: 选中文档中的所有E,无论在什么位置
>>>response.xpath('//a')
- E1//E2: 选中E1后代节点中的所有E2,无论在后代中的什么位置
>>>response.xpath('/html/body//img')
- E/text(): 选中E的文本子节点
>>>response.xpath('/html/body/div/a/text()')
- E/*:选中E的所有元素子节点
>>>response.xpath('/html/body/*')
- */E:选中孙节点中的所有E
>>>response.xpath('//div/*/img')
- E/@ATTR: 选中E的ATTR属性
>>>response.xpath('//img/@src')
- //@ATTR: 选中文档中所有ATTR属性
>>>response.xpath('//@href')
- E/@*: 选中E的所有属性
>>>response.xpath('//a[1]/img/@*')
- node[谓语]:谓语用来查找某个特定的节点或者包含某个特定值得节点
response.xpath('//a[3]') #选中所有a中的第三个
response.xpath('//a[last()]') #使用last函数,选中最后1个
response.xpath('//a[position()<=3]') #使用position函数,选中前三个
response.xpath('//div[@id]') #选中所有含有id属性的div
response.xpath('//div[@id="images"]') #选中所有含有id属性且值为“images”的div