显示异常的 findElement 方法

findElement method showing an exception

我需要单击一个有 50% 几率出现的按钮,因此决定使用 try/catchfindElementBy。然而 try/catch 不起作用,我遇到了一个例外。也许有更有效的方法来处理该按钮?

driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
WebDriverWait wait = new WebDriverWait(driver,5);
try {
    WebElement element = driver.findElement(By.xpath("buttonXpath"));
    element.click();
}
catch (NoSuchElementException e){ }

使用方法检查此元素是否在您的屏幕上:

if (!driver.findElementsByXPath("buttonXpath`enter code here`").isEmpty()) {
   driver.findElementByXPath("buttonXpath`enter code here`").click();
}

您可能会看到 NoSuchElementException,这可能由于很多原因而发生。您可以在

中找到详细的讨论

解决方案

最好的方法是根据以下讨论构建一个 which uniquely identifies the desired element with in the HTML DOM

  • How to inspect element for Selenium v3.6 as FireBug is not an option any more for FF 56?
  • FirePath not displaying HTML code after typing x-path

现在根据最佳实践,在调用 click() 时总是会在 elementToBeClickable()try-catch{} 块中诱导 WebDriverWait,如下所示:

try{
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("buttonXpath"))).click();
    System.out.println("Element was clicked")
}
catch (TimeoutException e){ 
    System.out.println("Element wasn't clicked") 
}

这对你有用:

List<Webelement> element = driver.findElements(By.xpath("buttonXpath"));

if(element.size() > 0) {
    element.get(0).click();
}