这是代码
for (loopVal = 1; loopVal < endVal; loopVal++) {
MobileElement followButton = (MobileElement) driver.findElement(By.xpath("//android.widget.ListView[@index='0']//android.widget.FrameLayout[@index='"+loopVal+"']//android.widget.LinearLayout[@index='0']//android.widget.FrameLayout[@index='2']//android.widget.TextView[@index='0']"));
String followOrNot = followButton.getText();
System.out.println(followOrNot + " " + loopVal);
}
如果没有找到 MobileElementfollowButton
,则会抛出错误,并且其余代码将不会执行
我需要在程序在 followButton
上运行 .getText()
之前检查 followButton
是否存在
如果我尝试用 try-catch block 包围 followButton
try {
MobileElement followButton = (MobileElement) driver.findElement(By.xpath("//android.widget.ListView[@index='0']//android.widget.FrameLayout[@index='"+loopVal+"']//android.widget.LinearLayout[@index='0']//android.widget.FrameLayout[@index='2']//android.widget.TextView[@index='0']"));
} catch(org.openqa.selenium.NoSuchElementException e) {
//handle error
}
然后我在 String followOrNot.getText()
上收到一个错误,上面写着
followButton cannot be resolved
如果我尝试在 followButton
上使用 .isEmpty
MobileElement followButton = (MobileElement) driver.findElement(By.xpath("//android.widget.ListView[@index='0']//android.widget.FrameLayout[@index='"+loopVal+"']//android.widget.LinearLayout[@index='0']//android.widget.FrameLayout[@index='2']//android.widget.TextView[@index='0']"));
if(driver.findElements(followButton).isEmpty()) {
//handle error
}
然后我在 findElements
上收到一个错误,内容为
The method findElements(By) in the type AppiumDriver is not applicable for the arguments (MobileElement)
如果我尝试在 followButton
上使用 .isDisplayed
MobileElement followButton = (MobileElement) driver.findElement(By.xpath("//android.widget.ListView[@index='0']//android.widget.FrameLayout[@index='"+loopVal+"']//android.widget.LinearLayout[@index='0']//android.widget.FrameLayout[@index='2']//android.widget.TextView[@index='0']"));
if(followButton.isDisplayed()) {
//do nothing
} else {
//handle error
}
那么现在的问题是,如果没有找到 followButton
,则会抛出错误,认为其余代码无用
我试图在 followButton
上执行任何其他操作之前验证 followButton
是否存在
我问了一个与此类似的问题,但没有收到有用的答案,我唯一的选择就是再次提问。
有人可以帮忙吗?
最佳答案
您可以通过首先获取该元素的列表然后检查列表大小来检查该元素是否存在于页面上。如果大小大于零,则该元素存在,否则不存在。
你可以这样做:
if(driver.findElements(By.xpath("//android.widget.ListView[@index='0']//android.widget.FrameLayout[@index='"+loopVal+"']//android.widget.LinearLayout[@index='0']//android.widget.FrameLayout[@index='2']//android.widget.TextView[@index='0']")).size()>0){
// Element is present
// Do the operations here
}
else{
// Element is not present
}
关于java - 如何检查 MobileElement 是否显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764146/