Appium+java 获取元素状态

时间:2023-03-08 16:47:47
Appium+java 获取元素状态
元素的属性我们经常会用到,当定位到某个元素后,有时会需要用到这个元素的text值、className、resource-id、checked等。 
一般标准的属性我们都可以通过get_attribute(“属性名称”)来获取,我们来看看下面截图的元素都是怎么获取的吧。从上到下来看。
Appium+java 获取元素状态

我们从text开始讲,我们先通过xpath方式定位到这个元素

public class UIdemoTest {
private AndroidDriver driver; @Before
public void setUp() throws Exception {
//设置并启动“app”
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "apps");
File app = new File(appDir, "com.sdu.doo.gsui.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("noReset", true);//不需要每次安装app
capabilities.setCapability("deviceName", "85GBBMD22AJY");
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("platformVersion", "5.1");
capabilities.setCapability("autoGrantPermissions","ture");//允许在手机上安装该app
capabilities.setCapability("appPackage", "com.sdu.doo.gsui");
capabilities.setCapability("appActivity", "com.doo.driver.sdk.LauncherActivity");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), (Capabilities) capabilities); } @After
public void tearDown() throws Exception {
} @Test
public void login () throws InterruptedException {
// clearText(By.xpath());
driver.findElement(By.xpath("//android.widget.EditText[@resource-id='com.sdu.didi.gsui:id/et_phone' and @text = '请输入手机号码']")).click();
driver.pressKeyCode(8);driver.pressKeyCode(8);driver.pressKeyCode(7);driver.pressKeyCode(7);driver.pressKeyCode(7);
driver.pressKeyCode(7);driver.pressKeyCode(7);driver.pressKeyCode(7);driver.pressKeyCode(13);driver.pressKeyCode(15);
driver.pressKeyCode(8);
Thread.sleep(1000);
// WebElement element = (WebElement) By.xpath("//android.widget.CheckBox[@resource-id='com.sdu.didi.gsui:id/cb_law' and @checked = 'false']");
// WebElement element1 = (WebElement) By.id("com.sdu.didi.gsui:id/cb_law");
WebElement element = driver.findElement(By.xpath("//android.widget.CheckBox[@text = '同意']"));
System.out.println(element.getAttribute("checked"));
if (element.getAttribute("checked") == "false"){
driver.findElement(By.id("com.sdu.didi.gsui:id/cb_law") ).click();//同意
}
driver.findElement(By.id("com.sdu.didi.gsui:id/btn_next")).click();//下一步
}
依次获取元素状态的方法有: element.getAttribute("checked")
element.getAttribute("text")
element.getAttribute("resource-id")
element.getAttribute("name")  name是获取content-desc的值
element.size()
element.location()
 
以此类推...

特注意一点:元素里只要属性值是布尔型的,即false or true。都可以通过这个方法来获取,就不一一列出了。这里的第二种方法经常用到,重点掌握!!

声明:本文为博主学习感悟总结,水平有限,如果不当,欢迎指正。如果您认为还不错,欢迎转载。转载与引用请注明作者及出处。