Appium - 检查元素是否存在

Appium - Check if element exist

我正在尝试使用 Appium (C#) 检查我的应用程序 (React Native) 中是否存在某个元素。我相信使用 .Displayed 是最好的做法,但是,当元素不存在时会抛出 NoSuchElementException

我能想到的唯一解决方法是用 try/catch 包装 .FindElement* 方法。这是检查元素是否存在的最佳方法,还是我错过了更好的方法?

private AndroidElement Name => Driver.FindElementByXPath("//*[@text='John Doe']");

public void OpenMenu()
{
    Utils.Log("Opening menu");
    if (!Name.Displayed)
        ToggleButton.Click();
}

谢谢!

.Displayed 告诉您该元素是否 可见 ,而不是 present/exists。它抛出的原因是因为当元素不存在时,您的 .Find* 失败。如果该元素存在但不可见,您也会得到漏报。在这种情况下,最佳做法是使用 .Find* 的复数形式,例如FindElementsByXPath(),并检查集合是否为空。如果不为空,则元素存在。

private IEnumerable<AppiumWebElement> Name => Driver.FindElementsByXPath("//*[@text='John Doe']")

然后检查集合是否为空

// requires LINQ
if (Name.Any())
{
    // element exists, do something
}

如果您不想使用 LINQ

if (Name.Count() > 0)

根据 Appium docs,您应该避免使用 XPath。

XPath | Search the app XML source using xpath (not recommended, has performance issues)