make wait function do something on and on if it fails - java

I am very beginner with Selenium and Java to write tests.
I know that I can use the code below to try to click on a web element twice (or as many time as I want):
for(int i=0;i<2;i++){
try{
wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//button[text()='bla bla ..']"))).click();
break;
}catch(Exception e){ }
}
but i was wondering if there is anything like passing a veriable to the wait function to make it do it ith times itself, something like:
wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//button[text()='bla bla ..']"),2)).click();
For example in here 2 may mean that try to do it two times if it fails, do we have such a thing?

Take a look at FluentWait, I think this will cover your use case specifying appropriate timeout and polling interval.
https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

If you can't find something in the set of ExpectedConditions that does what you are wanting you can always write your own.
The WebDriverWait.until method can be passed either a com.google.common.base.Function or com.google.common.base.Predicate. If you create your own Function implementation then it's good to note that any non-null value will end the wait condition. For Predicate the apply method simply needs to return true.
Armed with that I do believe there's very little you can't do with this API. The feature you're asking about probably does not exist out of the box, but you have full capability to create it.
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicate.html
Best of Luck.
Untested Snippet
final By locator = By.xpath("");
Predicate<WebDriver> loopTest = new Predicate<WebDriver>(){
#Override
public boolean apply(WebDriver t) {
int tryCount = 0;
WebElement element = null;
while (tryCount < 2) {
tryCount++;
try {
element = ExpectedConditions.visibilityOfElementLocated(locator).apply(t);
//If we get this far then the element resolved. Break loop.
break;
} catch (org.openqa.selenium.TimeoutException timeout) {
//FIXME LOG IT
}
}
return element != null;
}
};
WebDriverWait wait;
wait.until(loopTest);

Related

Explicit wait return strange findElement value

I'm trying to create a explicit wait method in my framework to handle the user's input. The method is supposed to handle all types of search: id, xpath, and css.
However, When I tried testing this method, the error is returning an odd error
Method of explicit wait
public static void isDisplaying(String variable){
wait = new WebDriverWait(driver,3);
System.out.println("Looking for: " + variable);
if (driver.findElement(By.id(variable)).isDisplayed()){
System.out.println("Found variable via id");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(variable)));
} else if (driver.findElement(By.xpath(variable)).isDisplayed()) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(variable)));
System.out.println("Found variable via xpath");
} else if (driver.findElement(By.cssSelector(variable)).isDisplayed()){
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(variable)));
System.out.println("Found variable via css");
} else {
System.out.println(variable +" is not displayed.");
}
}
Error that I'm receiving:
org.openqa.selenium.NoSuchElementException: Unable to locate element: #\/\/div\[\#id\=\'slideOut\-nav\'\]\/ul\/li\[2\]\/a
I have no clue why it is returning the value with all those back and forward slashes. My guess is that the application failed as soon as it tried searching the xpath string using id. But shouldn't it be moving to the next else if statement? How should I handle such issue, if this is indeed the issue?
When I simply locate the element and clicking, it works fine and returns the correct path:
//div[#id='slideOut-nav']/ul/li[2]/a
I've been stuck on this issue for a loooooong time so any help would greatly be appreciated!!
The call to driver.findElement(By.id(variable)) is bound to throw exceptions immediately if the element is not found.
Try replacing calls to driver.findElement() with driver.findElements() because this call does not throw exceptions but it returns an empty list of webelements when the call fails.
If you are really looking at building a generic method, then you should first parse the variable contents to see if it represents xPath or css and finally fall back to using id (or) name.
You can take a look at this implementation for reference.
I am not sure what your function is intended to do. You are checking to see if the element is displayed and if it is then wait for it to be displayed. If an element is displayed, it's already visible.
Instead of passing a String around, pass a locator, By. Passing a locator reduces having to check all the different locator types.
I've added a return type of boolean to your function so you can reuse it. It waits for up to 3 seconds for the element to be visible. If it doesn't timeout, the element is visible and it returns true. If it does time out, the element is not visible and returns false. You can reduce your code to the below.
public static boolean isDisplaying(By locator)
{
try
{
new WebDriverWait(driver, 3).until(ExpectedConditions.visibilityOfElementLocated(locator));
return true;
}
catch (TimeoutException e)
{
return false;
}
}
You would call it like
System.out.println(isDisplaying(By.xpath("//div[#id='slideOut-nav']/ul/li[2]/a")));
or
System.out.println(isDisplaying(By.id("someId")));
public void waitUntilElementclickable(WebElement element){
//Waits Until Element is Clickable on screen
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
}

How do I determine if a WebElement exists with Selenium?

I know I could use (driver.findElements(By.xpath("Xpath Value")).size() != 0);
However, I am using a Page Object Model, whose entire purpose is to predefine the WebElements in a separate class, so I don't have to "FindElements By" in my test classes.
Here's what I currently have
if (objPage.webElement.isEnabled()){
System.out.println("found element");
}else{
System.out.println("element not found");
}
However, this tries to identify the possibly non-existent WebElement. When it is not present, I get:
No Such Element" exception.
Best practice is to do what you originally suggested. Use .findElements() and check for .size != 0, or you can also use my preference, .isEmpty(). You can create a utility function like the below to test if an element exists.
public boolean elementExists(By locator)
{
return !driver.findElements(locator).isEmpty();
}
You could also build this into a function in your page object.
You can use isDisplayed() to check whether or not an element is visible. It’s trivial enough to write a method which will do what you want. Something like:
public boolean isElementDisplayed(WebElement element) {
try {
return element.isDisplayed();
} catch(NoSuchElementException e) {
return false;
}
}

Selenium exception handling, problems

I have problems with Java Selenium. I use it to automate testing web page, which structure is very complicated - a lot of elements are loaded dynamically, there is a lot of unnecessary elements in html pages. It's very difficult to make my tests reliable. Sometimes page can't load or I try to click on the button which doesn't exist yet (in similiar method of course).
So, I wrote Util class with methods like this one:
public static void findAndSendKeys(String vToSet, By vLocator) {
log.info("findAndSendKeys " + vLocator.toString());
int attempts = 0;
while (attempts < ATTEMPTS) {
WebElement element = null;
try {
element = webDriverWait.until(ExpectedConditions.presenceOfElementLocated(vLocator));
element.sendKeys(vToSet);
break;
} catch (TimeoutException e) {
log.error("timeOut exception " + e.getMessage());
} catch (StaleElementReferenceException e) {
log.error("StaleElementReference exception " + e.getMessage());
} catch (UnhandledAlertException e) {
log.error("UnhandledAlert exception " + e.getMessage());
Alert alert = driver.switchTo().alert();
alert.accept();
}
attempts++;
}
}
I know it looks terrible, I didn't refactor it yet, but method usually works fine for most cases - on the second or third loop input field is filled.
Firstly I was using only sendKeys with exception handling, but I noticed that although input field exists, StaleElementReferenceException is thrown, so I put while() in this static method and try to sendKeys again.
Sometimes my webPage shows Alert that is just validation and after catching exception and ignoring alert I can continue work.
I wonder.. It could be easier if there would exist method similiar to "Pause 1000" method in Selenium IDE. Sometimes my web page works fast and good, sometimes page loading process is very long and I have to wait.
There is also problems with while() loop. I don't know what to do if while loop ends and nothing is send - for example loaded page/container is blank, dynamic loading fails, so there is no chance to find our input field
Automate testing process for this web page causes me a headache. Please, be placable, I don't have technical support and I am on my own.
In my opinion, you are trying to overengineer the whole thing. I think you are trying to write a single function that will handle all cases and I don't think that is a good approach. Each case is potentially different and you will need to understand each case and handle it appropriately.
A few tips.
Don't loop a wait.until(). Instead of
for (int i = 0; i < 5; i++)
{
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(...);
}
do
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(...);
The end result is the same (max 50s wait) but the 2nd code is less confusing. Read up on waits to better understand them. The default behavior for a wait is to wait up to the max time and poll the condition every 500ms.
If you are getting StaleElementReferenceException, you are missing something. I don't mean that to sound critical... it happens. You need to understand how the HTML of the page is changing because you are looking for an element that is disappearing and then you try to scrape it. You will need to change either the element you are looking for or when you are looking for it.
Don't use Thread.sleep(). In general it's a bad practice because it's hard coded. Depending on the environment, it may be too long or not long enough of a wait. Instead prefer the wait.until() mechanism you are already using. The hard part, at times, is finding what to wait for.
If you are trying to scrape the page after the items are sorted, then you need to determine what changes after sorting occurs. Maybe there's an arrow on the column header that appears to indicate a sort direction (ascending vs descending)? One thing you could do is to grab one of the TD elements, wait for it to go stale (while the elements are being sorted), and then regrab all elements?
Maybe something like this
WebDriverWait wait = new WebDriverWait(driver, 10);
// grab the first TD as a stale reference
WebElement td = driver.findElement(By.tagName("td"));
// wait for it to go stale
wait.until(ExpectedConditions.stalenessOf(td));
// now grab them all and do something with them
List<WebElement> tds = driver.findElements(By.tagName("td"));
Without a link to the page or a lot more explanation of what is happening on the page and some relevant HTML, I'm not sure what else we can provide.
This code works for me:
jsPageLoadWait ="
try {
if (document.readyState !== 'complete') {
return false; // Page not loaded yet
}
if (window.jQuery) {
if (window.jQuery.active) {
return false;
} else if (window.jQuery.ajax && window.jQuery.ajax.active) {
return false;
} else if ($(':animated').length != 0) {
return false;
}
}
if (window.angular) {
if (!window.qa) {
// Used to track the render cycle finish after loading is complete
window.qa = {
doneRendering: false
};
}
// Get the angular injector for this app (change element if necessary)
var injector = window.angular.element('body').injector();
// Store providers to use for these checks
var $rootScope = injector.get('$rootScope');
var $http = injector.get('$http');
var $timeout = injector.get('$timeout');
// Check if digest
if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {
window.qa.doneRendering = false;
return false; // Angular digesting or loading data
}
if (!window.qa.doneRendering) {
// Set timeout to mark angular rendering as finished
$timeout(function() {
window.qa.doneRendering = true;
}, 0);
return false;
}
}
return true;
} catch (ex) {
return false;
}"
public static Boolean WaitLoad(this ISearchContext context, UInt32 timeoutInMilliseconds = 10000, UInt32 millisecondPolling = 1000)
{
Boolean waitReadyStateComplete;
var wait = new DefaultWait<ISearchContext>(context);
wait.Timeout = TimeSpan.FromMilliseconds(timeoutInMilliseconds);
wait.PollingInterval = TimeSpan.FromMilliseconds(millisecondPolling);
wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(StaleElementReferenceException));
waitReadyStateComplete = wait.Until<Boolean>(ctx =>
{
if ((Boolean)((IJavaScriptExecutor)context).ExecuteScript(jsPageLoadWait))
return true;
else
return false;
});
return waitReadyStateComplete;
}

Which is the correct way to check if an element is present or displayed on a page with Selenium WebDriver using Java?

I'm testing a web application using Selenium WebDriver and I was wondering which is the proper method to check if the elements are present or displayed. I usually assert that all elements are present on the page but it also checks the hidden elements which in this case would also be necessary to check if the elements are displayed only when some action is done. For example I click a link and other fields and labels are displayed, while they were hidden before. In this case I should both check if the elements are present and also if they are or not displayed before and after some other element is clicked.
I was wondering which is the proper way to do this. Is it too much to check all the elements on the page ( assuming that I have some buttons, text-fields, labels, links etc. in the page)?
For the purpose of discussion I want to include some code snippets. To check that elements are present on the page I use the following snippet:
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
To check if an element is displayed I use the following snippet:
public boolean isElementDisplay(By by) {
if (driver.findElement(by).isDisplayed()) {
return true;
} else
return false;
}
One purpose of testing this application is to check if the elements exists and are displayed correctly. Am I doing the right thing here? Please give me your point of view. I've recently started working with Selenium WebDriver and being the only one in my company who does this...I don't have anyone to turn to. Any answer is appreciated.
There are no problems with it, except if you call your "checkIfDisplayed" method on an element that doesn't exist in the first place, it will throw an exception. I would modify it to this:
public boolean checkIfDisplayed(By by) {
if (isElementPresent(by) {
if (driver.findElement(by).isDisplayed()) {
return true;
} else
return false;
} else
return false;
}
(This may not be code that compiles, I am a C# man, but you should see what I mean)
It may have a slight performance hit, but overall what you are doing is perfectly fine anyway.
To check for element's existence I'd rather use
public boolean isElementPresent(By by)
{
return driver.findElements(by).size() > 0
}
I don't really get the idea behind your checkIfDisplayed function. It returns the result returned by WebElemet's isDisplayed() method without adding any new functionality...
EDIT
So far Arran provided the best answer. Just to modify it a little bit:
public boolean checkIfDisplayed(By by)
{
List<WebElemet> elements = driver.findElements(by);
return ((elements.size() > 0) && (elements[0].isDisplayed()));
}
I believe however that it would be better to call isElementPresent and isDisplayed separately. In this way you will know why the test failed (if it was caused by element's existence or visibility)
I use the same approach (I mean the same methods). But it is important to understand two things.
Some element can be present but not visible.
So for the purpose to verify whether element is present we can call the method
public boolean isElementPresent(By locatorKey) {
try {
driver.findElement(locatorKey);
return true;
} catch (NoSuchElementException e) {
return false;
}
But the drawback of isElementPresent method it can point out elements in DOM model that are not visible on the page and consequently are not accesssible with webDriver. So in that case additional check helps us:
driver.findElement(By.xpath(....)).isDisplayed()
Hope things come clear now)
I'd say your first method looks just fine.
The 2nd thus will give you trouble if the findElement-call will give you no result.
You should add a check if there is an element found and then check if it's displayed:
try {
final WebElement elem = driver.findElement(by);
elem.isDisplayed();
return true;
} catch (NoSuchElementException nse) {
return false;
}
Also note: You are ignore the possibility that more than one element matches the criteria given by the by instance. See the findElemts() method.
You can also combine both the methods as per your requirement as follows,
if(driver.findElements(By.LOCATOR).size()>0)
{
if(driver.findElement(By.LOCATOR).isDisplayed())
{ print "Element is present and displayed"; }
else
{ print "Element is present but not displayed"; }
}
else
{ print "Element is not present"; }

Test if an element is present using Selenium WebDriver

Is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay. That is not a fail of the test, so an exception can not be the solution.
I've found this post: Selenium C# WebDriver: Wait until element is present.
But this is for C#, and I am not very good at it. What would the code be in Java? I tried it out in Eclipse, but I didn't get it right into Java code.
This is the code:
public static class WebDriverExtensions{
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){
if (timeoutInSeconds > 0){
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
Use findElements instead of findElement.
findElements will return an empty list if no matching elements are found instead of an exception.
To check that an element is present, you could try this
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
This will return true if at least one element is found and false if it does not exist.
The official documentation recommends this method:
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
Use a private method that simply looks for the element and determines if it is present like this:
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
This would be quite easy and does the job.
You could even go further and take a By elementLocator as a parameter, eliminating problems if you want to find the element by something other than an id.
I found that this works for Java:
WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);
public static WebElement FindElement(WebDriver driver, By by, int timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until( ExpectedConditions.presenceOfElementLocated(by) ); //throws a timeout exception if element not present after waiting <timeoutInSeconds> seconds
return driver.findElement(by);
}
I had the same issue. For me, depending on a user's permission level, some links, buttons and other elements will not show on the page. Part of my suite was testing that the elements that should be missing, are missing. I spent hours trying to figure this out. I finally found the perfect solution.
It tells the browser to look for any and all elements based specified. If it results in 0, that means no elements based on the specification was found. Then I have the code execute an *if statement to let me know it was not found.
This is in C#, so translations would need to be done to Java. But it shouldn’t be too hard.
public void verifyPermission(string link)
{
IList<IWebElement> adminPermissions = driver.FindElements(By.CssSelector(link));
if (adminPermissions.Count == 0)
{
Console.WriteLine("User's permission properly hidden");
}
}
There's also another path you can take depending on what you need for your test.
The following snippet is checking to see if a very specific element exists on the page. Depending on the element's existence I have the test execute an if else.
If the element exists and is displayed on the page, I have console.write let me know and move on. If the element in question exists, I cannot execute the test I needed, which is the main reasoning behind needing to set this up.
If the element does not exist and is not displayed on the page, I have the else in the if else execute the test.
IList<IWebElement> deviceNotFound = driver.FindElements(By.CssSelector("CSS LINK GOES HERE"));
// If the element specified above results in more than 0 elements and is displayed on page execute the following, otherwise execute what’s in the else statement
if (deviceNotFound.Count > 0 && deviceNotFound[0].Displayed){
// Script to execute if element is found
} else {
// Test script goes here.
}
I know I'm a little late on the response to the OP. Hopefully this helps someone!
Try this:
Call this method and pass three arguments:
WebDriver variable. Assuming driver_variable as the driver.
The element which you are going to check. It should provide a from By method. Example: By.id("id")
Time limit in seconds.
Example: waitForElementPresent(driver, By.id("id"), 10);
public static WebElement waitForElementPresent(WebDriver driver, final By by, int timeOutInSeconds) {
WebElement element;
try{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); // Nullify implicitlyWait()
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Reset implicitlyWait
return element; // Return the element
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This works for me:
if(!driver.findElements(By.xpath("//*[#id='submit']")).isEmpty()){
// Then click on the submit button
}
else{
// Do something else as submit button is not there
}
You can make the code run faster by shorting the Selenium timeout before your try-catch statement.
I use the following code to check if an element is present.
protected boolean isElementPresent(By selector) {
selenium.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
logger.debug("Is element present"+selector);
boolean returnVal = true;
try{
selenium.findElement(selector);
} catch (NoSuchElementException e) {
returnVal = false;
} finally {
selenium.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
return returnVal;
}
Write the following function/methods using Java:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Call the method with the appropriate parameter during the assertion.
If you are using rspec-Webdriver in Ruby, you can use this script, assuming that an element should really not be present, and it is a passed test.
First, write this method first from your class RB file:
class Test
def element_present?
begin
browser.find_element(:name, "this_element_id".displayed?
rescue Selenium::WebDriver::Error::NoSuchElementError
puts "this element should not be present"
end
end
Then, in your spec file, call that method.
before(:all) do
#Test= Test.new(#browser)
end
#Test.element_present?.should == nil
If your element is not present, your spec will pass, but if the element is present, it will throw an error, and the test failed.
Personally, I always go for a mixture of the above answers and create a reusable static utility method that uses the size() > 0 suggestion:
public Class Utility {
...
public static boolean isElementExist(WebDriver driver, By by) {
return driver.findElements(by).size() > 0;
...
}
This is neat, reusable, maintainable, etc.—all that good stuff ;-)
public boolean isElementDisplayed() {
return !driver.findElements(By.xpath("...")).isEmpty();
}
This should do it:
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
//do what you need here if you were expecting
//the element wouldn't exist
}
I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):
object SeleniumFacade {
def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
val elements = maybeParent match {
case Some(parent) => parent.findElements(bySelector).asScala
case None => driver.findElements(bySelector).asScala
}
if (elements.nonEmpty) {
Try { Some(elements(withIndex)) } getOrElse None
} else None
}
...
}
so then,
val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))
The simplest way I found in Java was:
List<WebElement> linkSearch= driver.findElements(By.id("linkTag"));
int checkLink = linkSearch.size();
if(checkLink!=0) {
// Do something you want
}
To find if a particular Element is present or not, we have to use the findElements() method instead of findElement()...
int i = driver.findElements(By.xpath(".......")).size();
if(i=0)
System.out.println("Element is not present");
else
System.out.println("Element is present");
This is worked for me...
You can try implicit wait:
WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));
Or you can try explicit wait one:
IWebDriver driver = new FirefoxDriver();
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("someDynamicElement"));
});
Explicit will check if the element is present before some action. Implicit wait could be called in every place in the code. For example, after some Ajax actions.
More you can find at SeleniumHQ page.
I am giving my snippet of code. So, the below method checks if a random web element 'Create New Application' button exists on a page or not. Note that I have used the wait period as 0 seconds.
public boolean isCreateNewApplicationButtonVisible(){
WebDriverWait zeroWait = new WebDriverWait(driver, 0);
ExpectedCondition<WebElement> c = ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#value='Create New Application']"));
try {
zeroWait.until(c);
logger.debug("Create New Application button is visible");
return true;
} catch (TimeoutException e) {
logger.debug("Create New Application button is not visible");
return false;
}
}
In 2022 this can now be done without an annoying delay, or affecting your current implicit wait value.
First bump your Selenium driver to latest (currently 4.1.2).
Then you can use getImplicitWaitTimeout then set timeout to 0 to avoid a wait then restore your previous implicit wait value whatever it was:
Duration implicitWait = driver.manage().timeouts().getImplicitWaitTimeout();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(0));
final List<WebElement> signOut = driver.findElements(By.linkText("Sign Out"));
driver.manage().timeouts().implicitlyWait(implicitWait); // Restore implicit wait to previous value
if (!signOut.isEmpty()) {
....
}
Try the below code using the isDispplayed() method to verify if the element is present or not:
WebElement element = driver.findElements(By.xpath(""));
element.isDispplayed();
There could be multiple reasons due to which you might observe exceptions while locating a WebElement using Selenium driver.
I would suggest you to apply the below suggestions for different scenarios:
Scenario 1: You just want to find out if a certain WebElement is present on the screen or not. For example, the Save button icon will only appear until the form is fully filled and you may want to check if Save button is present or not in your test.
Use the below code -
public Boolean isElementLoaded(By locator){
return !getWebElements(this.driver.findElements(locator), locator).isEmpty();
}
Scenario 2: You want to wait before a WebElement becomes visible in the UI
public List<WebElement> waitForElementsToAppear(By locator) {
return wait.until(visibilityOfAllElementsLocatedBy(by));
}
Scenario 3: Your test is flaky because the WebElement becomes stale sometimes and gets detached from the DOM.
protected final List<Class<? extends WebDriverException>> exceptionList =
List.of(NoSuchWindowException.class,
NoSuchFrameException.class,
NoAlertPresentException.class,
InvalidSelectorException.class,
ElementNotVisibleException.class,
ElementNotSelectableException.class,
TimeoutException.class,
NoSuchSessionException.class,
StaleElementReferenceException.class);
public WebElement reactivateWebElement(By by, WebElement element){
try {
wait.ignoreAll(exceptionList)
.until(refreshed(visibilityOf(element)));
logger.info(("Element is available.").concat(BLANK).concat(element.toString()));
} catch (WebDriverException exception) {
logger.warn(exception.getMessage());
} return this.driver.findElement(by);
}

Categories