Selenium Scenario test - xpath 以及 元素基本操作

因为近期增加Scenario test,需要使用到Selenium,所以增加下使用频率较高的xpath和元素的基本操作,方便使用。

xpath

建议

  1. 最好使用相对路径
  2. 避免使用数字索引
  3. //后的第一个元素 尽量使用变化少、距离目标元素近的元素

xpath节点查找

/:表示从根目录开始的绝对路径(不建议)

//:从当前路径往下查找文档中的节点(子孙节点),即相对位置

1:选取第一个元素

last():选取最后一个元素

last()-1:选取倒数第二个元素

@class:拥有名为 class 属性的元素

@class="test":拥有名为 class 属性且该属性为 test 的元素

not(contains(text(), "test")):文本内容不包含 test 的元素(.等于text(),即可替换为not(contains(., "test"))

position()=last():当前节点的最后一个元素( position()为当前节点在同级节点中的位置 )

ancestor:祖先

descendant:子孙后代

parent:当前节点的父亲节点

child:当前节点的子节点

following:当前节点之后的所有节点

following-sibling:当前节点之后的所有兄弟节点

preceding:当前节点之前的所有节点

preceding-sibling:当前节点之前的所有兄弟节点

xpath节点查找案例

复制代码
//span[text()='确定']/ancestor::button[not(@disabled)]:查找文本为"确定"的<span>元素,再从这些<span>元素出发,向上查找其祖先元素中的<button>元素,且该<button>元素没有disabled属性

(//div[@class='item__label' and .//span/text()='key']/following-sibling::div//button)[1]:查找<div>元素属性class为'item__label'并且这个<div>元素内存在一个文本内容为key的<span>元素。接着这个<div>元素向下查找同级兄弟<div>元素中的<button>元素,取第一个<button>元素

元素基本操作

复制代码
element = driver.find_element(By.XPATH, "//span[text()='确定']/ancestor::button[not(@disabled)]")

# 相关操作
element.click(): 点击元素
element.clear(): 清除文本
element.send_keys(value): 输入文本
element.get_attribute(name): 获得属性值
element.is_displayed(): 返回元素结果是否可见(True 或 False)
element.is_selected(): 返回元素结果是否被选中(True 或 False)​
element.is_enabled(): 返回元素是否可用(True 或 False)

element.text: 元素的可见文本内容
相关推荐
2601_9622982714 小时前
Python与Selenium结合的Web自动化测试全流程实践教程
自动化测试·python·selenium·web测试·pageobjectmodel
2601_9622982721 小时前
【自动化测试】基于Selenium + Python的web自动化框架
自动化测试·python·selenium·测试用例·web框架
2601_962295582 天前
python+selenium实现自动化测试
自动化测试·python·selenium·学习心得·web端测试
B2_Proxy3 天前
Selenium配置代理IP的完整指南:从启动参数到认证扩展
selenium·测试工具
weixin_440730503 天前
Playwright介绍、特点、小例子还有与传统selenium的区别
selenium·测试工具·playwright
2601_962387825 天前
web自动化测试实战教程【selenium/unittest/pytest】【共193课
selenium·pytest·devops·web自动化测试·unittest
2601_962297255 天前
Python、Pytest、Allure、Selenium和Jenkins实现自动化测试集成实例
python·selenium·jenkins·pytest·allure
是吕先森5 天前
【python】selenium实现web自动化测试
前端·python·selenium
weixin_440730505 天前
selenium实战记录-从登陆-首页-进入应用流程用例三种参数化+日志+报告
服务器·selenium·测试工具
岁月失语唯石能言6 天前
《 Web项目测试实战:博客系统的功能/接口/自动化/性能全流程测试报告》
自动化测试·功能测试·selenium·jmeter·接口测试·压力测试·性能测试