attribute
选取当前节点的所有属性 。
child
选取当前节点的所有子元素 。
descendant
选取当前节点的所有后代元素(子、孙等) 。
descendant-or-self
选取当前节点的所有后代元素(子、孙等)以及当前节点本身 。
following
选取文档中当前节点的结束标签之后的所有节点 。
namespace
选取当前节点的所有命名空间节点 。
parent
选取当前节点的父节点 。
preceding
【Python解析库lxml与xpath用法总结】选取文档中当前节点的开始标签之前的所有节点 。
preceding-sibling
选取当前节点之前的所有同级节点 。
self
选取当前节点 。
5.xpath运算符
下面列出了可用在 XPath 表达式中的运算符:
描述
实例
返回值
|
计算两个节点集
//book | //cd
返回所有拥有 book 和 cd 元素的节点集
+
加法
6 + 4
10
-
减法
6 - 4
2
*
乘法
6 * 4
24
div
除法
8 div 4
2
=
等于
price=9.80
如果 price 是 9.80,则返回 true 。如果 price 是 9.90,则返回 false 。
!=
不等于
price!=9.80
如果 price 是 9.90,则返回 true 。如果 price 是 9.80,则返回 false 。
<
小于
price<9.80
如果 price 是 9.00,则返回 true 。如果 price 是 9.90,则返回 false 。
<=
小于或等于
price<=9.80
如果 price 是 9.00,则返回 true 。如果 price 是 9.90,则返回 false 。
>
大于
price>9.80
如果 price 是 9.90,则返回 true 。如果 price 是 9.80,则返回 false 。
>=
大于或等于
price>=9.80
如果 price 是 9.90,则返回 true 。如果 price 是 9.70,则返回 false 。
or
或
price=9.80 or price=9.70
如果 price 是 9.80,则返回 true 。如果 price 是 9.50,则返回 false 。
and
与
price>9.00 and price<9.90
如果 price 是 9.80,则返回 true 。如果 price 是 8.50,则返回 false 。
mod
计算除法的余数
5 mod 2
1
好了,xpath的内容就这么多了 。接下来我们要介绍一个神器lxml,他的速度很快,曾经一直是我使用beautifulsoup时最钟爱的解析器,没有之一,因为他的速度的确比其他的html.parser 和html5lib快了许多 。
二、lxml
1.lxml安装
lxml 是一个xpath格式解析模块,安装很方便,直接pip install lxml 或者easy_install lxml即可 。
2.lxml 使用
lxml提供了两种解析网页的方式,一种是你解析自己写的离线网页时,另一种 则是解析线上网页 。
导入包:
from lxml importetree 1.解析离线网页:
html=etree.parse('xx.html',etree.HTMLParser())aa=html.xpath('//*[@id="s_xmancard_news"]/div/div[2]/div/div[1]/h2/a[1]/@href')print(aa)2.解析在线网页:from lxml import etreeimport requestsrep=requests.get('https://www.baidu.com')html=etree.HTML(rep.text)aa=html.xpath('//*[@id="s_xmancard_news"]/div/div[2]/div/div[1]/h2/a[1]/@href')print(aa)那么我们怎么获取这些标签和标签对应的属性值了,很简单,首先获取标签只需你这样做:
文章插图
推荐阅读
- Python生成密码字典,配合解密使用
- 一篇文章教会你使用Python定时抓取微博评论
- Python反射介绍
- Python 语言Django 框架的简化视图
- Vuestic UI - 免费开源的 Vue3 组件库,内置漂亮的 Admin 后台框架
- mysql误删除恢复
- 解析:阳台为何不能正对大门或厨房
- Python对象及内存管理机制
- Linux系统中的库
- python学习笔记之基础循环语句
