html_doc = '''<html> <head></head> <body> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> </body> </html>'''
1、路劲查找html
描述 | |
---|---|
nodename | 选取此节点的子节点。 |
/ | 从根节点选取。 |
// | 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。 |
. | 选取当前节点。 |
.. | 选取当前节点的父节点。 |
@ |
from lxml import etree page = etree.HTML(html_doc) page.xpath('/html') # 从跟节点查找 page.xpath('//book') # 从全部节点查找 page.xpath('//book')[0].xpath('..') # 选取当前节点的父节点 page.xpath('//book')[0].xpath('@category') # 选取属性
node
表达式 | 结果 |
---|---|
nodename[1] | 选取第一个元素。 |
nodename[last()] | 选取最后一个元素。 |
nodename[last()-1] | 选取倒数第二个元素。 |
nodename[position()<3] | 选取前两个子元素。 |
nodename[@lang] | 选取拥有名为 lang 的属性的元素。 |
nodename[@lang='eng'] |
page.xpath('//book[2]/@category') # 选取第二个book元素 page.xpath('//book[last()-2]/@category') # 选取倒数第三个book元素 page.xpath('//book[position() > 1]/@category') # 选取第二个元素开始的全部元素 page.xpath('//book[@category="WEB"]/@category') # 选取category属性为WEB的的元素
3、未知节点函数
描述 | |
---|---|
* | 匹配任何元素节点。 |
@* |
page.xpath('//book[1]/*') page.xpath('//book//title[@*="en"]')
4、xpath的运算符spa
运算符 | 描述 |
| | 计算两个节点集 |
or | 或 |
and | 与 |
not | 非 |
page.xpath('//book[1]|//book[2]') # 同时获取book1和book2的标签 # 输出:[<Element book at 0x289bac27048>, <Element book at 0x289bac27088>] page.xpath('//book[@category="WEB" and @cover="paperback"]') # 获取同时拥有category和cover属性的book标签 page.xpath('//book[@category="WEB" or @cover="paperback"]') # 获取拥有 category 或 cover 属性的book标签 page.xpath('//book[not(@category="cooking")]') # 获取属性不是category="cooking"的book标签
5、亲属关系code
表达式 | 描述 |
parent::*
|
表示当前节点的父节点元素
|
child::*
|
表示当前节点的子元素
|
following-sibling::*
|
表示当前节点的后序全部兄弟节点元素
|
preceding-sibling::*
|
表示当前节点的前面全部兄弟节点元素
|
page.xpath('//book/parent::*') # 表示获取book节点的父节点标签 page.xpath('//book/child::*') # 表示获取book节点的全部子节点 page.xpath('//book[1]/child::title') # 表示获取第一个book节点下名称为title的子节点 page.xpath('//book[1]/following-sibling::*') # 表示获取第一个book节点后序的兄弟节点(不包含自己) page.xpath('//book[3]/preceding-sibling::book') # 表示获取第三个book节点前面的且名称为book的兄弟节点
6、经常使用函数xml
表达式 | 描述 |
last() |
返回当前上下文中的最后一个节点的位置号数。
|
contains()
|
模糊查询 |
page.xpath('//book[last()]') # 获取最后一个book标签 page.xpath('//book[contains(@category, "co")]') # 模糊匹配属性category="co"的book标签