APP 自动化之appium元素定位(三)

 APP自动化测试关键环节--元素定位,如下咱们来了解appium提供的元素定位方法!java

1. id定位,id一个控件的惟一标识,由开发人员在项目中指定,若是一个元素有对应的resource-id,咱们就能够采用这种方式来实现元素定位操做,可是实际开发中,也有可能app项目的开发人员不是很严谨,一个页面有不少个相同的id,获取到的元素结果是一个集合,因此这种状况咱们须要用list进行接收android

//找到想要定位的元素并进行点击
androidDriver.findElement(By.id("id")).click();

2. text 定位,java-client旧版本提供了相应的API支持session

//根据text属性进行定位
androidDriver.findElement(By.name("登陆"));

注意:java-client新版本运行以后会发现定位失败,这是由于java-client 5.0 之后新版本不支持这个API:app

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: Locator Strategy 'name' is not supported for this session (WARNING: The server did not provide any stacktrace information)

解决方案:框架

androidDriver.findElementByAndroidUIAutomator("new UiSelector().text(\"登陆\")");

注意提示:ide

由于:测试

解决办法:Configure Build Path jdk1.8 ui

配置后:this

3. className 定位。根据class类查找元素,通常获得的是多个元素(除非className惟一),若是获得多个,咱们须要用一个List集合接收返回值spa

//根据className属性进行定位
List<WebElement> listElement = androidDriver.findElements(By.className(("className"))); listElement.get(1).click();

4. xpath 定位

//根据xpath属性进行定位
androidDriver.findElement(By.xpath("//android.widget.Button[@text='登陆']")).click(); androidDriver.findElement(By.xpath("//android.widget.Button[@text=\"登陆\"]")).click();

5. accessibility id 元素定位 

//根据AccessibilityId进行定位
androidDriver.findElementByAccessibilityId("登陆").click();

6. 坐标定位:经过开发者选项>>指针位置或者是UIAutomatorView获取到的位置(绝对坐标)

//坐标定位 //经过TouchAction类完成坐标点击
TouchAction touchAction = new TouchAction<>(androidDriver); //将(x,y)坐标封装成PointOption对象传入tap方法调用
PointOption pointOption =PointOption.point(500, 500); //经过调用tap方法进行点击.调用perform()方法执行点击
touchAction.tap(pointOption).perform();

7. UIAutomator 定位,安卓的UIAutomator是一个强有力的元素定位方式,它是经过Android提供的原生的UIAutomator框架去找元素,且支持元素所有属性定位,appium提供的定位元素API其实都是UIAutomator提供的API,appium元素定位方式以下:

//经过UIAutomator 的description 方法找到属性是 content-desc 的元素
androidDriver.findElementByAndroidUIAutomator("new UiSelector().description(\"登陆\")").click(); //经过UIAutomator的text 方法找到属性是text的元素
androidDriver.findElementByAndroidUIAutomator("new UiSelector().text(\"登陆\")").click(); //经过UIAutomator的 resourceId方法找到属性是 resourceID的元素
androidDriver.findElementByAndroidUIAutomator("new UiSelectot().resourceId(\"resource-id\")").click();

 8.未完待续.......