您的当前位置:首页>全部文章>文章详情

xpath 介绍

发表于:2021-09-30 15:20:03浏览:65次TAG: #前端

web driver 提供了八种元素定位的方法
id / name / class name / tag name
link text / partial link text (部分链接文本) / xpath / css selector

xpath 介绍

基本定位方法

路径表达式
表达式 描述
nodename 选取此节点的所有子节点
/ 从根节点选取
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
. 选取当前节点
.. 选取当前节点的父节点
@ 选取属性
使用 id 定位
<input type="text" id="username" value="">

//input[@id="username"]
使用 class 定位
<input type="text" class="username" value="">

//input[@class="username"]
路径绝对定位
# 以 / 开头,从跟目录开始,比较繁琐,一般不建议使用
<html>
    <body>
        <div>
            <a href="http://xxxx.com"></a>
        </div>
    </body>
</html>

/html/body/div/a
路径相对定位
# 以 // 开头
<html>
    <body>
        <div>
            <a href="http://xxxx.com"></a>
        </div>
    </body>
</html>

//div/a
# 双/表示留空// == /(html/body/..)/div/a
文本定位 - text()
<button type="button" class="btn btn-primary">登录</button>

//button[text()='登录']
模糊定位 - contains()
<button type="button" class="btn btn-primary">登录</button>

# 只取 class 的 btn 部分
//button[contains(@class,"btn")]

最后一个节点定位 - last()

# 选择id中包含有'in'的div节点的最后一个节点
//div[contains(@id, 'in')][las()]
逻辑定位
# 使用 starts-with 匹配以xx开头的属性; ends-width 匹配以xx结尾的属性值

//button[starts-width(@class, "btn")]
//button[starts-end(@class, "btn-primary")]
逻辑运算符
# 使用 and / or 运算符
//button[@name="submit" and @data-type="m"]

否定 - not()

# 匹配出name为identity并且class的值中不包含a的input节点
//input[@name='identity' and not(contains(@class,'a'))]

# 匹配出input节点含有id属性的
// input[@id]
# 匹配出input节点不含用id属性的
//input[not(@id)]
索引定位
# 索引从 1 开始
<html>
    <body>
        <div>
            <a href="http://xxxx.com"></a>              <- [1]
            <a href="http://xxxx.com"></a>              <- [2]
        </div>
    </body>
</html>

/html/body/div/a[1]
/html/body/div/a[2]

取数据

取文本 - text()
# 获取节点下第五个a标签的内容
//div[@id="list"]/a[5]/text()

# 获取节点下不带标签下所有内容
//div[@id="list"]//text()
取属性
# 获取节点下第五个a标签的href属性
//div[@id="list"]/a[5]/@href
栏目分类全部>
腾讯云采购季云服务器一折促销