简体   繁体   中英

findElement method showing an exception

i'm need to click a button which may appear with a 50 percent chance, decided to use try/catch with findElementBy . Nevertheless try/catch doesn't work and I'm getting an exception. Maybe there is a more efficient way to handle that button?

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){ }

Possibly you are seeing NoSuchElementException which can happen due to a lot of reasons. You can find a detailed discussion in NoSuchElementException, Selenium unable to locate element


Solution

The best approach would be to construct a Locator Strategy which uniquely identifies the desired element with in the HTML DOM following the discussions in:

Now as per best practices while invoking click() always induce induce WebDriverWait with in a try-catch{} block for the elementToBeClickable() as follows:

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") 
}

This will work for you:

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

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

Use method to check if this element is on your screen:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM