XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。xpath中节点之间的关系有父(parent)、子(children)、同胞(sibling)、先辈(ancestor)、后代(descendent)。xpath的具体教程可以在wc3school中学习。
在Python中xpath属于lxml库,因此需先安装lxml库。
实例:
from lxml import etreetxt =''' 我的公众号2019年 python
欢迎关注每日一Python
共同进步
谢谢
'''html = etree.HTML(txt)r = html.xpath("//h1/a/@href") #获取属性用@xxprint(r)
![8ba2b6d1cde03c269351f5087e6eca51.png](https://img-blog.csdnimg.cn/img_convert/8ba2b6d1cde03c269351f5087e6eca51.png)
r2 = html.xpath("//title/@lang")print(r2)
![25e2f6b3a342bdcdd8771a851ede8667.png](https://img-blog.csdnimg.cn/img_convert/25e2f6b3a342bdcdd8771a851ede8667.png)
r3 = html.xpath("//comment()") #获取注释用comment()print(r3)
![2c4eada62e1f8061b82e6f4aca290fb4.png](https://img-blog.csdnimg.cn/img_convert/2c4eada62e1f8061b82e6f4aca290fb4.png)
r4 = html.xpath("//gzh/year/text()") #获取文本内容用text()print(r4)
![d7ed5a91e17e464d3bf6432cb299a397.png](https://img-blog.csdnimg.cn/img_convert/d7ed5a91e17e464d3bf6432cb299a397.png)
r5=html.xpath("//p")print(r5)#可以看到HTML中有两个P,若是想获取第一个和最后一个p呢#获取第一个pprint(r5[0].text)或者r6 = html.xpath("//p[1]/text()")
![9132dfe828f7a7c9dc24c00f873e83be.png](https://img-blog.csdnimg.cn/img_convert/9132dfe828f7a7c9dc24c00f873e83be.png)
#获取最后一个p,利用last()r7 = html.xpath("//p[last()]/text()")print(r7)
![e7bbf0ab2998aa374c689c92bb0a43c8.png](https://img-blog.csdnimg.cn/img_convert/e7bbf0ab2998aa374c689c92bb0a43c8.png)