XPath 是一门在 XML 文档中查找信息的语言。可用来在 XML 文档中对元素和属性进行遍历
话不多说,直接讲技术点。
-
技术要点
- 选取节点
列出了一些路径表达式以及表达式的结果,如下:
- 谓语
谓语是来查找某个特定的节点或者包含某个指定的值得节点
谓语被嵌在后面的方括号中 - .选取未知节点
- 选取若干路径
- 选取节点
-
使用
- 首先我们使用 lxml 的 etree 库,然后利用 etree.HTML 初始化,然后我们将其打印出来
其中,这里体现了 lxml 的一个非常实用的功能就是自动修正 html 代码,大家应该注意到了,最后一个 li 标签,其实我把尾标签删掉了,是不闭合的。不过,lxml 因为继承了 libxml2 的特性,具有自动修正 HTML 代码的功能。所以输出结果是这样的,不仅补全了 li 标签,还添加了 body,html 标签。
代码:from lxml import etree text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> ''' html = etree.HTML(text) result = etree.tostring(html) print(result) 结果:
- 获取<li>标签
代码:
··· ···html = etree.HTML(text) result = etree.tostring(html) # print(result) obj = html.xpath('//li') print(obj) print(type(obj)) 结果: [<Element li at 0x1510a08>, <Element li at 0x1510a88>, <Element li at 0x1510ac8>, <Element li at 0x1510b08>, <Element li at 0x1510b48>] <class 'list'> Process finished with exit code 0
- 获取<li>标签的所有class
代码:''' html = etree.HTML(text) result = etree.tostring(html) # print(result) obj = html.xpath('//li/@class') print(obj) print(type(obj)) 结果: ['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0'] <class 'list'> Process finished with exit code 0
- 获取 <li> 标签下 href 为 link1.html 的 <a> 标签
代码:''' html = etree.HTML(text) result = etree.tostring(html) # print(result) obj = html.xpath('//li/a/@href') print(obj) print(type(obj)) 结果: ['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html'] <class 'list'> Process finished with exit code 0
- 获取 <li> 标签下的所有 <a> 标签
代码:''' html = etree.HTML(text) result = etree.tostring(html) obj = html.xpath('//li/a') print(obj) print(type(obj)) 结果: [<Element a at 0x1510a08>, <Element a at 0x1510a88>, <Element a at 0x1510ac8>, <Element a at 0x1510b08>, <Element a at 0x1510b48>] <class 'list'> Process finished with exit code 0
- 获取最后一个 <li> 的 <a> 的 href
代码:''' html = etree.HTML(text) result = etree.tostring(html) obj = html.xpath('//li[last()]/a/@href') print(obj) print(type(obj)) 结果: ['link5.html'] <class 'list'> Process finished with exit code 0
- 获取倒数第二个元素的内容
代码:''' html = etree.HTML(text) result = etree.tostring(html) obj = html.xpath('//li[last()-1]/a')[0].text print(obj) print(type(obj)) 结果: fourth item <class 'str'> Process finished with exit code 0
- 获取 li下的class 为 bold 的标签名
代码:''' html = etree.HTML(text) result = etree.tostring(html) obj = html.xpath('//li[@class="item-0"]') print(obj) print(type(obj)) 结果: [<Element li at 0x1520a08>, <Element li at 0x1520a88>] <class 'list'> Process finished with exit code 0
xpath 的大部分的技术点都总结了,有不足之处,欢迎来电。。。——————>电话号码是:
不告诉你
- 首先我们使用 lxml 的 etree 库,然后利用 etree.HTML 初始化,然后我们将其打印出来