【Appium】使用uiautomator定位元素
介绍:appium可以使用uiautomator 来定位元素,或者滚动页面。使用uiautomator 只适用于Android。
下面以appium官方自带的调试App来演示。
调试App下载地址:https://github.com/appium/appium/blob/master/sample-code/apps/ApiDemos-debug.apk
通过className定位
通过classname获取第一个实例
driver.findElementByAndroidUIAutomator("new UiSelector().className(\"android.widget.TextView\").instance(1)");
通过text定位
如上图,现在定位Views这个元素,它的text属性值也为“Views”,那就可以使用如下定位:
driver.findElementByAndroidUIAutomator("new UiSelector().text(\"Views\")");
滑动页面直到找到对应的元素
如上图,Popup Menu元素需要往下滑动页面才能看到。uiautomator提供滚动屏幕,直到找到目标元素的方法。有以下两种方式:
第一种:
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))" +
".getChildByText(new UiSelector().className(\"android.widget.TextView\"), \"Popup Menu\")")
第二种:
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))." +
"scrollIntoView(new UiSelector().text(\"Popup Menu\").instance(0));")
完整代码:
package test.java.cases;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import test.java.common.InitDriver;
import test.java.common.OperateElement;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/** * Author: 灵枢 * Date: 2019/11/22 * Time: 9:34 * Description: */
public class UIAutomatorTest {
private AndroidDriver driver;
@BeforeClass
public void setUp() throws Exception{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("noReset",true);
capabilities.setCapability("unicodeKeyboard",true);
capabilities.setCapability("autoGrantPermissions",true);
capabilities.setCapability("appPackage","io.appium.android.apis");
capabilities.setCapability("appActivity",".ApiDemos");
//初始化
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
// 设置隐式等待时间
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass()
public void tearDown() {
driver.quit();
}
@Test
public void testUiSelector(){
// 通过text查找
driver.findElementByAndroidUIAutomator("new UiSelector().text(\"Views\")").click();
// 滑动屏幕查找,第一种方式
/* String orderNo = driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))" + ".getChildByText(new UiSelector().className(\"android.widget.TextView\"), \"Popup Menu\")").getText(); System.out.println(orderNo);*/
// 滑动屏幕查找,第二种方式
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))." +
"scrollIntoView(new UiSelector().text(\"Popup Menu\").instance(0));").click();
OperateElement.threadSleep(3000);
}
}
代码运行如下:
还没有评论,来说两句吧...