Appium的常用定位方法

使用uiautomatorviewer.bat工具来找到属性定位元素,在SDK的tools目录下找到该工具,双击打开。左边框内展示app的界面元素,右上角框内展示元素的层级关系,右下角框内展示元素的属性。

1.使用id定位元素

resource-id代表id属性,使用方法:

driver.findElement(By.id("com.android.calculator2:id/digit5")).click();//点击5

2.使用name定位元素

text代表name属性,使用方法:

driver.findElement(By.name("5")).click();

3.使用class定位元素

class就是class属性,class属性定位出元素有可能有很多,定位到某一个元素需要其他条件,使用方法:

  1. @Test
  2. public void testcase3(){
  3. List<WebElement> list = driver.findElements(By.className("android.widget.Button"));
  4. for (WebElement elem:list){
  5. System.out.println(elem);
  6. }
  7. }

4.使用xpath定位元素

需要注意:Appium中属性class的代表标签的名字,下标是从1开始的。

元素的属性具有唯一性时:

driver.findElement(By.xpath("//android.widget.TextView[contains(@resource-id,'com.android.mms:id/action_compose_new')]")).click();
driver.findElement(By.xpath("//android.widget.TextView[@text='New message']")).click();

xpath定位中的标签之间的父子关系和兄弟关系:

图中框1中的三个标签是兄弟关系,框2中的两个标签为父子关系。

兄弟关系:

如果想定位最后一个LinearLayout,可以使用preceding-sibling::表示定位当前标签的哥哥标签,following-sibling::表示定位当前标签的弟弟标签,方法如下:

        driver.findElement(By.xpath("//android.widget.FrameLayout[1]/following-sibling::android.widget.FrameLayout[2]")).click();

通过following-sibling找到第一个标签LinearLayout的第二个弟弟,也就是定位第三个LinearLayout标签。

同理定位第一个标签,通过找到第三个标签的第二个哥哥,就是第一个LinearLayout标签。

driver.findElement(By.xpath("//android.widget.FrameLayout[3]/preceding-sibling::android.widget.FrameLayout[2]")).click();

上面的两种情况可能不适合使用preceding-sibling::和following-sibling::,只是用来举例它们的使用方法。

父子关系:

如果想定位TextView标签,可以使用parent::或者..表示父亲标签,定位框2中的TextView标签。

        driver.findElement(By.xpath("//android.widget.FrameLayout[2]/parent::android.view.View/android.widget.FrameLayout[3]/android.widget.TextView")).click();

通过parent::找到第二个LinearLayout的父标签View,父标签的第三个子标签LinearLayout的第一个子标签就是TextView标签。

5.Accessibility ID定位,Appium的扩展方法

找到元素的content-desc属性来定位。

  1.        driver.findElement(By.name("7")).click();
  2. driver.findElementByAccessibilityId("divide").click();
  3. driver.findElement(By.name("2")).click();
  4. driver.findElementByAccessibilityId("equals").click();

6.使用AndroidAutomator定位,Appium的扩展方法

description就是content-desc属性。  

  1.         driver.findElementByAndroidUIAutomator("new UiSelector().text("9")").click();
  2. driver.findElementByAndroidUIAutomator("new UiSelector().description("plus")").click();
  3. driver.findElementByAndroidUIAutomator("new UiSelector().resourceId("com.android.calculator2:id/digit6")").click();
  4. driver.findElementByAndroidUIAutomator("new UiSelector().description("equals")").click();

参考博客:https://testerhome.com/topics/7129

https://www.cnblogs.com/testway/p/6225415.html

http://www.testclass.net/appium/appium-base-find-element/#

原文地址:https://www.cnblogs.com/tiechui2015/p/10310738.html