You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Appium Java中实现元素存在则点击、不存在则关闭应用的方法

实现方式1:通过捕获不存在元素异常处理

Appium 调用findElement方法时,如果找不到对应元素会直接抛出NoSuchElementException,可以通过捕获该异常走分支逻辑:

import org.openqa.selenium.NoSuchElementException;

try {
    MobileElement el2 = (MobileElement) driver.findElementByAccessibilityId("New Account");
    el2.click();
} catch (NoSuchElementException e) {
    // 元素不存在,直接关闭应用
    driver.closeApp();
}

实现方式2:结合显式等待处理(推荐)

如果要避免页面还未加载完成就误判元素不存在,可以搭配显式等待使用,适配页面加载延迟的场景:

import io.appium.java_client.AppiumBy;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

// 自定义最大等待时长,单位可自行调整
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
try {
    wait.until(ExpectedConditions.presenceOfElementLocated(AppiumBy.accessibilityId("New Account")));
    MobileElement el2 = (MobileElement) driver.findElement(AppiumBy.accessibilityId("New Account"));
    el2.click();
} catch (org.openqa.selenium.TimeoutException e) {
    // 等待超时判定元素不存在,关闭应用
    driver.closeApp();
}

注意:如果你使用的是Appium 8.x及以上版本,原生的findElementByAccessibilityId方法已废弃,推荐使用AppiumBy.accessibilityId的写法。

内容的提问来源于stack exchange,提问作者Ibrahim Abo-salim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:36:06