[英]Appium - Check if element exist
I am trying to check if an element exist or not in my application (React Native) with Appium (C#).我正在尝试使用 Appium (C#) 检查我的应用程序 (React Native) 中是否存在某个元素。 I beleive using .Displayed
is the best practice for this, however, this throws an NoSuchElementException
when the element does not exist.我相信使用.Displayed
是最好的做法,但是,当元素不存在时,这会引发NoSuchElementException
。
The only workaround I can think of for this is to wrap the .FindElement*
method with a try/catch
.我能想到的唯一解决方法是用try/catch
包装.FindElement*
方法。 Is this the best method for checking if an element exist, or am I missing a better approach?这是检查元素是否存在的最佳方法,还是我错过了更好的方法?
private AndroidElement Name => Driver.FindElementByXPath("//*[@text='John Doe']");
public void OpenMenu()
{
Utils.Log("Opening menu");
if (!Name.Displayed)
ToggleButton.Click();
}
Thanks!谢谢!
.Displayed
tells you whether the element is visible , not present/exists. .Displayed
告诉您元素是否可见,不存在/存在。 The reason it's throwing is because when the element is not there, your .Find*
fails.它抛出的原因是因为当元素不存在时,您的.Find*
失败。 You would also get false negatives if the element was present but not visible.如果元素存在但不可见,您也会得到误报。 Best practice in cases like this is to use the plural form of .Find*
, eg FindElementsByXPath()
, and check to see if the collection is empty.在这种情况下,最佳做法是使用.Find*
的复数形式,例如FindElementsByXPath()
,并检查集合是否为空。 If it's not empty, the element is present.如果它不为空,则元素存在。
private IEnumerable<AppiumWebElement> Name => Driver.FindElementsByXPath("//*[@text='John Doe']")
Then to check if the collection is empty然后检查集合是否为空
// requires LINQ
if (Name.Any())
{
// element exists, do something
}
If you don't want to use LINQ如果您不想使用 LINQ
if (Name.Count() > 0)
Per the Appium docs , you should avoid using XPath.根据Appium 文档,您应该避免使用 XPath。
XPath | XPath | Search the app XML source using xpath (not recommended, has performance issues)使用 xpath 搜索应用程序 XML 源(不推荐,有性能问题)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.