-4

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){ }
Guy
  • 46,488
  • 10
  • 44
  • 88
Vadim Popov
  • 49
  • 1
  • 8
  • 1
    Can you show the exception stacktrace? Please add also your imports, especially that one of the NoSuchElementException. – AndiCover Dec 11 '19 at 11:58
  • What is the exception you are getting? `NoSuchElementException`? – Guy Dec 11 '19 at 11:58

3 Answers3

0

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") 
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • The OP never said the exception he is getting is `NoSuchElementException`. – Guy Dec 11 '19 at 12:35
  • @Guy Well, you can see OP trying to handle _NoSuchElementException_ in his code trials. – undetected Selenium Dec 11 '19 at 12:36
  • Yes, and he says he still have an exception despite the `try catch`. Unless he used the wrong import he has another exception. But you can't know which one is it without more details. – Guy Dec 11 '19 at 12:38
  • there is no `TimeoutException` what do you want to achieve? – Vault23 Dec 11 '19 at 13:00
0

This will work for you:

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

if(element.size() > 0) {
    element.get(0).click();
}
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
-2

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();
}
Vault23
  • 743
  • 1
  • 5
  • 19
  • You are performing the Xpath query twice. Store the list of elements and access the first element of it, when it is not empty. – AndiCover Dec 11 '19 at 12:02
  • feel free to do whatever you want with this list. My example is just showing the way to avoid exception – Vault23 Dec 11 '19 at 12:05