'Element not found, continue test

I have a page that randomly displays windows before homepage, to enter the site, I sometimes need to complete the form, so I use :

@FindBy(xpath = "") public WebElement element;

Then i try to implement solution, but it fail.

if(element.isDisplayed()){ 
element.click();
}else if {
do something else // if not Displayed do something else and get test true?
}

Get error:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element

In my project i use java, cucumber nad testNG. I have no idea how to do that, when it does not find a form on the page, it continues the test. Maybe I should do more methods or scenarios?



Solution 1:[1]

The error message means it cannot find the element.

Few things,

  1. Do you have the right selector for that element?
  2. Does the webpage use JQuery or AngularJS? If so, you need to wait for them to load
  3. Are you using any type of wait? Before checking if the element exist on the page? (ex. ImplicitWait, FluentWait, Thread.sleep [bad practice])

Try this -> driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

This waits for an element to load up to 10 seconds before not finding it.

Solution 2:[2]

1) You need to use something like this:
public WebElement [] elements = driver.findElementsBy(xpath = "The Xpath you are looking for");
if (elements)
In case the randomly displayed window appear your list will not be empty, will contain an element you are looking for. Otherwise the list will be empty.
Your code fails since your are looking for an element that not always existing in the page.
2) You can also use Try - Catch

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zahidul Islam
Solution 2