python + appium 自动化测试方案 — 元素定位

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_shashadudu/article/details/82117337

自动化测试最基础的就是元素定位,找到牢靠的定位方式,可以增强自动化测试框架的兼容性。


1、利用appium查看对应元素

打开appium并点击搜索按钮。

这里写图片描述

填写连接app所需要的信息,点击“start session”按钮启动查找控件界面。

这里写图片描述

在元素查看界面可以找到对应的属性。

这里写图片描述

2、常用的元素查找方式

- 通过元素id定位
driver.find_element_by_id('com.example.zhuowendi.demotest:id/btn_rv')
- 通过元素Name定位(元素的名称属性text)
driver.find_element_by_name('recyclerview')
- 通过元素class name属性定位元素
driver.find_element_by_class_name('android.widget.Button')
- 通过Xpath定位元素
driver.find_element_by_xpath('/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.View/android.widget.FrameLayout[2]/android.widget.LinearLayout/android.widget.Button')
- 通过AccessibilityId定位

在 Android 上,主要使用元素的content-desc属性,如该属性为空,不能使用此定位方式。
在 iOS 上,主要使用元素的label或name(两个属性的值都一样)属性进行定位,如该属性为空,也是不能使用该属性。
由于相同app在不同的手机上元素的属性会发生变化,所以推荐使用此定位方式实现精准定位,只是需要在代码中为元素添加content-desc属性。

driver.find_element_by_accessibility_id('***')

3、xpath使用小贴士

由于一开始对python语法的入门是爬数据,所以在没有特殊情况时,个人更偏向使用xpath定位元素。

- xpath基本语法:
表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。
- xpath与其他属性相结合
###xpath与text相结合:
driver.find_element_by_xpath("//*[@text='recyclerview']")

###xpath与id结合:
driver.find_element_by_xpath("//*[@resource-id='com.example.zhuowendi.demotest:id/btn_rv']")

###xpath与class结合:
driver.find_element_by_xpath("//*[@class='android.widget.Button']")
- xpath的层级关系
###通过父元素定位子元素:
driver.find_element_by_xpath("//*[@resoure-id="android:id/content"]/android.widget.LinearLayout")

###通过子元素定位父元素:
driver.find_element_by_xpath("//*[@resource-id="com.example.zhuowendi.demotest:id/btn_rv"]/..")
driver.find_element_by_xpath("//*[@resource-id="com.example.zhuowendi.demotest:id/btn_rv"]/parent::*")
driver.find_element_by_xpath("//*[@resource-id="com.example.zhuowendi.demotest:id/btn_rv"]/parent::android.widget.LinearLayout"

以此扩展,可以通过多层级关系定位到元素。

- path路径定位到多个元素

若path路径相同的元素有多个,可以通过添加下标来筛选第几个元素。

###定位第一个button按钮:
driver.find_element_by_xpath("//android.widget.Button[1]")

###定位列表下的全部列表项:
items = driver.find_elements_by_xpath("//android.support.v7.widget.RecyclerView/*[@class='android.widget.TextView']")

猜你喜欢

转载自blog.csdn.net/Mr_shashadudu/article/details/82117337