1、定位原理
我们一般使用Python或Java语言调用相关的Client,那么Appium里就会通过Webdriver协议(Selenium里同样)在应用层进行HTTP方式的数据请求,那么收到请求的手机上的Appium APP的Server就会解析相关的请求并且使用Appium提供的相应自动化测试方法去驱动手机做出相应的操作。
这里为了方便,我才用QQ的登录页面来说明
2、定位方式
笔者再接触自动化的时候,find_element_by_xxxxx 此类方法已弃用,我这里选择selenium中的定位方法
2.1、id定位
id(resource-id)一般来说是唯一的,可以直接使用
代码示例:
import time
from appium import webdriver
from selenium.webdriver.common.by import By
desired_capabilities = {
"platformName": "Android",
"appium:platformVersion": "12",
"appium:devicesName": "AXMN6R2729001833",
"appium:appPackage": "com.tencent.mobileqq",
"appium:appActivity": "com.tencent.mobileqq.activity.SplashActivity"
}
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_capabilities)
time.sleep(3)
# 找到【同意】按钮并点击
driver.find_element(By.ID, "com.tencent.mobileqq:id/dialogRightBtn").click()
2.2、className定位
className不太推荐,界面中相同类型的元素重复的概率很大,无法准确定位,较少使用
driver.find_element(By.CLASS_NAME, "android.widget.TextView")
2.3、text定位
控件里面的文本值,也不一定是唯一的
driver.find_element(By.NAME, "输入QQ密码")
2.4、accessibility_id定位
这个是用来描述当前元素的功能的,类似于备注,这个属性值一般为空,实用性不高。
# 这个还能用
driver.find_element_by_accessibility_id("密码 安全")
2.5、xPath定位
这种定位方式比较万金油
推荐使用xpath定位方式,只不过极度不推荐使用绝对路径的定位方式,大量的绝对路径定位方式会使脚本或框架在后期的维护上造成很大的难度与较高的成本
//android.widget.AutoCompleteTextView[@content-desc="请输入QQ号码或手机号或QID或邮箱"]
这里我不用这个,我用text
以下是一个相对定位的写法:
driver.find_element(By.XPATH, "//android.widget.AutoCompleteTextView[@text='QQ号/QID/邮箱/手机号']")
下面也属于相对定位:
driver.find_element(By.XPATH, "//android.widget.AutoCompleteTextView[contains(@text,'QQ号/QID/邮箱/手机号')]")
下面也是用xpath,有点儿组合定位的意思
driver.find_element(By.XPATH, "//*[@class='android.widget.AutoCompleteTextView' and @text='QQ号/QID/邮箱/手机号']")
4、AppiumBy定位
现在主流的也有AppiumBy定位的,差不多的用法,比如以下
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
driver = webdriver.Remote('http://localhost:4723/wd/hub', xxxxxxx)
driver.find_element(AppiumBy.ID('com.jiyong.rta.debug:id/edt_customer_name'))
其实定位方式都是大同小异,也就语法是不同的,这个知道定位方式和定位原理即可,语言、库类只是实现的工具