In my learning curve I have been looking at the right way to wait for an element to be loaded and you get lots of pages on google.
Got down to 2 but in my view Method2(ExpectedConditions.ElementIsVisible) is more elegant and does what method1 is trying to achieve do you agree or is there a better way?
Method 1
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);
}
Method 2
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
var element = wait.Until(ExpectedConditions.ElementIsVisible(by));
return element;
}
Any suggestions or improvements also what happens if "NoFoundElement exception is thrown is it already handled or should I ignore it?
I would say yes, "Method 2" is the preferred way of doing it. Simply because if something is already implemented in WebDriver, there's no need for you to reimplement it in your testing framework.
As to your question regarding the NotFoundException: If the condition that you're waiting for isn't met after the specified timeout, the WebDriverWait will raise a WebDriverTimeoutException. Depending on the condition that you wanted to wait for, the WebDriverTimeoutException will have an inner exception with more details. If for example you use ExpectedConditions.ElementIsVisible(By.Id("myid")) and the element couldn't be located at all, the inner exception will be a NoSuchElementException. If the element could be located but isn't visible after the given timeout you'll just get the WebDriverTimeoutException.
Depending on what you want to do once you're sure that the element is "there", you can also use different ExpectedConditions. If the element you're waiting for is a button and you want to click on it, you can use ExpectedConditions.ElementToBeClickable as this will not only wait for the element to get loaded into the DOM and visible, but also wait for the element to get enabled.
Related
Please comment the following code I found on YouTube. It checks whether an element is present at the time
public boolean isElementPresent(By locator)
{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
List<WebElement> list = driver.findElements(locator);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
if (list.size() == 0)
return false;
else
return list.get(0).isDisplayed();
}
It dynamically changes implicitlyWait in the method. In all Selenium resources are always stated that the implicitWait can be set only once in the test class. The code above is similar to some extent to the explicit wait since it adapts to different situations.
What is your opinion about this code?
In the Selenium documentation it is said that Once set, the implicit wait is set for the life of the session.
However, in the code above we change the implicitlyWait twice.
Is the documentation wrong?
Implicit wait
The Implicit wait is to notify the WebDriver instance to poll the HTML DOM for a certain amount of time when trying to find an element or elements if they are not immediately available within the DOM Tree.
Once set, the implicit wait is set for the life of the session
Yes, you saw it right. That's because implicit waits are implemented on the remote side of the WebDriver system. That means they are baked in to GeckoDriver, ChromeDriver, IEDriverServer, etc WebDriver variants that gets installed into the anonymous Firefox/Chrome profile, and the Java remote WebDriver server. However, you can always re-configure the implicitlyWait.
You can find a detailed discussion in Using implicit wait in selenium
This usecase
Syntactically, your code is flawless. Ideally, you would set the implicitlyWait while looking out for the desired elements. Once the elements are ideantified and stored in a list you can reset the implicitlyWait back to 0. So effectively your code block will be:
public boolean isElementPresent(By locator)
{
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List<WebElement> list = driver.findElements(locator);
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
if (list.size() == 0)
return false;
else
return list.get(0).isDisplayed();
}
After reviewing the selenium docs, I am wondering if I am attempting to implement explicit waits incorrectly.
In the docs, it always shows identifying a new element, then assigning the defined wait to said element
WebDriver driver = new ChromeDriver();
driver.get("https://google.com/ncr");
driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
// Initialize and wait till element(link) became clickable - timeout in 10 seconds
WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));
// Print the first result
System.out.println(firstResult.getText());
In this example, a new element firstResult is created, then the defined wait assigned to it.
Is this required? Should always be done this way?
This is why I ask.
I am using the PageFactory model and have my elements defined via the FindBy annotation, as shown here.
// Input field for slice ID
#FindBy(how = How.XPATH, using = "//input[#name='id']")
private WebElement inputSliceId;
Then, in that same class, I have defined some convenience methods to use them.
So now, in my convenience methods, should I do things like this?
inputSliceId = new WebDriverWait(driver, Duration.ofSeconds(10))...
inputSliceId.sendKeys(...
What I have been doing, which is what I'm questioning now, is putting wait statements that are not being assigned directly to the element in question.
For example, I've been doing things like this.
buttonSubmit.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#role='alertdialog']")));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[#role='alertdialog']")));
Why? (could totally be wrong here)
Upon clicking the button, I need to wait for a pop-up to display
Once it does, I am then waiting for it to disappear, before proceeding
Here's the main question
Are these two wait lines not really doing anything because I am not assigning them to an element? Or are they still causing the web driver to hold until the conditions specified by the wait occur?
No, You can't assigned wait statement as above to your web element. If you want to wait for your element using Page factory model for a below element then you have to create
public void isLoaded() throws Error {
// Initial loading, called when creating the page object to make sure that the page is loaded to a state where it is ready to interact with us, in our case it means that button is present in DOM and visible.
public class BaseClass
{
private void waitForVisibility(WebElement element) throws Error{
new WebDriverWait(driver, 60)
.until(ExpectedConditions.visibilityOf(element));
}
}
And then in your page object model class you can extend this BaseClass.
public class page extends BaseClass
{
#FindBy(how = How.XPATH, using = "//input[#name='id']")
private WebElement inputSliceId;
waitForVisibility(inputSliceId);
}
I have defined wait in the BaseClass to achieve re-usability of waitForVisibility code across all page object classes.
Also after button clicking if you want to wait for a pop up to be appear then you can include code like below:
#FindBy(xpath = "//div[#role='alertdialog']")
private WebElementFacade alertPopup;
buttonSubmit.click();
waitForVisibility(alertPopup);
There are a couple of things:
If your usecase is to invoke getText() on an element, instead of elementToBeClickable(), using visibilityOfElementLocated() would be just perfect.
To extract the text you don't have to create any new element, instead you can directly invoke visibilityOfElementLocated() once the element is returned as follows:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a/h3"))).getText());
If your usecase doesn't include any validation for the pop-up which gets displayed and disappear, you don't need to induce any waiter for it and safely ignore it. So once you invoke click() on the buttonSubmit you can proceed to your next validation point adjusting the timespan for the pop-up to be displayed and disappear.
So, your optimized code block will be:
buttonSubmit.click();
// consider the total timespan for the wait to be cumulative of: pop-up displayed + pop-up disappear + next interactable element to become clickable
new WebDriverWait(driver, Duration.ofSeconds(20)).until(ExpectedConditions.elementToBeClickable(By.xpath("xpath_next_element_to_click")));
You can find a relevant detailed discussion in How to add explicit wait in PageFactory in PageObjectModel?
First, you can declare a method where set up the wait itself, in a separate class used like base or parent, like that:
protected void waitForElementToBeLoaded(WebElement element) {
wait.until(ExpectedConditions.elementToBeClickable(element));
}
Then, you can declare a second method where use the first one, in a separate class used like fictional page, like that:
public void sendMessageForm( ){
waitForElementToBeLoaded(sendBtn);
sendBtn.click();
}
Finally, every time you use the previous method the wait will be triggered, example:
contactUsPage.sendMessageForm();
I have a table with several rows. Some of these rows may have a specific element and others may not. For sure some will and some won't.
I find the row and have it into a WebElement. Now to see whether an element is there I do the following (assume xp = ".//someelement)
List<WebElement> eles = row.findElements(By.xpath(xp));
if (eles.size() == 0) {
// element is not there
} else {
// element is there
}
This is fine when the element is present. When it is not, it takes like 30 seconds or a minute to figure out that it is not there. If called often this can really slow down the test. I can do
try {
WebElement ele = row.findElement(by.xpath(xp));
} catch (Exception ex) {
// element is not there
}
using a more detailed Exception. This works fine too but same problem. It waits a minute or half a minute.
Is there a way to check more quickly whether an element is present or not? If it were relative to driver (driver.findElementBy()) instead of an element (row.findElementBy()) I think I might know how to do it.
This is Java.
In your first example where you have a List of Elements you are not trying to locate one element; but several (let's say a collection of rows instead of one row). The second element ele is finding (or trying to find) a specific item (let's say 1 row). Hence, ideally you should say in your comments that some elementS were not there for eles . Nevertheless, the time issue is probably down to an implicit or explicit wait. Read here for more.
I prefer the first way where you check for a collection of elements (so you can aim it at a xpath and find all the tags included (or none at all). Ideally though you should go for an explicit wait.
Here is the method for waiting, it will return true/or false based on if the element was present during the polling time (10sec for example); worth noting that if the element is found as present earlier than the 10sec limit the loop will break and will return true. Of course you can play with timeOut to achieve the desired result; don't go to fast though (like 2 sec) otherwise you are risking your test occasionally failing because the tables were not loaded yet:
public boolean waitForElement(String elementXpath, int timeOut) {
try{
WebDriverWait wait = new WebDriverWait(driver, timeOut);
boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());
System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
}
catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}
return elementPresent;
}
I'm guessing that you are already using an explicit wait of 30sec for all of your findElement attempts hence the discrepancy.
Hope the above helps,
Best of luck!
Another option is to use WebDriverWait (explicit waits) rather than implicit ones.
This basically makes it so your tests will only wait a long time when you tell them too, otherwise they'll instantly fail if they don't find the elements you're looking for.
Adapted from slide52 of tourdedave's slideshare
// Use this class whenever you have to access the driver
// And you should only have to setDriver in a BeforeMethod when setting up.
// This method shows how to do it with a single browser
// This could be converted quite easily to threadlocals for parallel test runs
public class DriverManager {
private final WebDriver driver;
public static WebDriver getDriver() {
return driver;
}
public static setDriver(WebDriver driver) {
DriverManager.driver = driver;
}
public class WaitUntil {
public static Boolean displayed(By locator, Integer... timeout) {
try {
waitFor(ExpectedConditions.visibilityOfElementLocated(locator),
(timeout.length = 0 : null ? timeout[0];
} catch (TimeoutException exception) {
return false;
}
return true;
}
// add additional methods you want to wait for
// Look at the source of the ExpectedConditions class to see how to create
// your own
// e.g. presence of element
// number of results from locator changes
// element done moving
// url changes, etc.
private static void waitFor(ExpectedCondition<WebElement> condition, Integer timeout) {
timeout = timeout != null ? timeout[0] : 5; //default timeout if no value given
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(condition);
}
}
Then in any class you can
By submitButtonBy = By.cssSelector(".submit);
use WaitUntil.displayed(submitButtonBy);
And it will wait for 5 seconds. If you want to wait for 10:
use WaitUntil.displayed(submitButtonBy, 10);
The nice thing about making a class with a bunch of methods like this is it's easy to add additional exceptions so you can choose to return false if there's a stale element or something else, rather than have to deal with a try catch in page classes or test classes.
So, I have a class A and it has a (public static WebElement element1, element2).
public class myClass {
public static WebElement element1, element2;
public myClass(){
WebDriver driver = new FirefoxDriver();
this.element1 = driver.findElement(By.id("button"));
this.element2 = driver.findElement(By.id("text"));
}
}
And then I have a test class where it has a method called #Test public void testClassA.
#Test
public void testClassA(){
myClass m = new myClass();
m.element1.click();
m.element2.sendKeys("input something");
}
Questions is I am getting org.openqa.selenium.NoSuchElementException: Unable to locate element:{} error. I think my error is happening because the element2 is located in the next page, it shows up after clicking the button. What should I do in my code so that when I assign both elements to findBy method the test is going through the first click and then sendKeys to element2?
The way you have written the code will break in scenarios where
elements are dynamic and also on page navigation.
This is not a good practice to find the webelement in different class altogether and use the object of that class in your test class.
As you can see in code: myClass m = new myClass();, when object of myClass is created, the constructor is triggered and driver finds both the element1 and element2 at once. And, since element2 is still not displayed, it throws an exception.
I don't know what prompted you to follow this practice, instead find the webelement only when you actually need it. There seems to be many alternative and it depends on how you want to design your code.
Use same class to find the element and performing action on that.
Use different methods to find the webelements, instead of using constructors to find them.
Use keywords for webdriver actions if you want to make things generic.
Use properties file to store the locators and dat if you want.
More Standard practice(I guess so):
Use Page Objects to find the webelements.
Use PageFactory in addition to Page Objects.
Good Reference: http://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html
As you mentioned that the element2 is present in the next page, you have to wait till the new page loads. Without this wait, if you try finding the element2, it will throw an exception as the element is not found on the current page before the page change.
Solutions:
1) Add a Explicit wait after the element1 click() method. You can wait till the element2 is present after the click().
m.element1.click();
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("text")));
m.element2.sendKeys("input something");
2) Simple but I would not recommend this. Use Thread.sleep() to wait for the new page to load.
3) Use Page Object Design Pattern.
You can use webdriver implicitwait to wait for the elements on the page to load for a certain period of time.
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
As you can see in the above code i used 8 seconds for the elemnets on the page to load. Read more about wait in Webdriver
Use a try catch block to handle the exception.
#Test
public void testClassA(){
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
try{
myClass m = new myClass();
m.element1.click();
m.element2.sendKeys("input something");
}catch(NoSuchElementException e){
e.printStackTrace();
}
}
I'm using Selenium Webdriver and have run into the following issue with my app under test.
The app has multiple pages each with an appropriate ".page-title" element which contains the name of the page (e.g. "Other Documents"). As the tests navigate around the app they assert that the browser is on the expected page using these elements before doing other stuff.
The issue is that if you click a button in the app which performs an action, then check that you're on the right page (e.g. check page-title element displays correct text), Webdriver doesn't wait for the action to be performed (e.g. new page load), it returns straight away and the test fails.
If you add a short thread sleep (500ms) between performing the action and checking you're on the right page, then you get StaleElementReferenceException (some of the time) and if you add a large thread sleep the test passes (but not quite all the time).
My aim is to reduce the flakiness of the tests, does anyone have a suggestion as to how I can do this without Thread.sleep?
instead of inserting thread.sleep method explicity
do try the WebDriver in built Implicitwait method..(C# code snippet)
Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Max_Time_Limit));
This makes WebDriver to wait till the element is visible/available. In case if it finds elements before the Max_Time_Limit, it snaps out of sleep mode and resumes the execution.
So no hassle of waiting till the Hard bound Max_Time_Limit.This way it helps speeding up your execution Time as well.
I hope this helps...All the best :-)
Try using this wait: using this you can wait for max time 15 secs/wait for the expected condition to be true i.e. wait for some element to be present.
You can give the xpath of some element on the next page, when that element is visible then the next step will be executed.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("\xpath of some element on the next page")));
//Assert page title
driver.getTitle();
use fluentWait mechanism . Considered to be a robust approach. As documentation on fluent wait gives:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
details you can get here
here is the code of method I use:
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
String xPathElement="...blablabla...";
fluentWait(By.xpath(xPathElement)).click();
//fluentWait(By.xpath(xPathElement)).getText();
Hope it works for you.
You can use Selenium's ExpectedCondition.
The code below (written in JAVA) waits for a maximum of inTimeout seconds for the element you want to appear. If the element appears sooner, it ends the wait.
public static void wait(WebDriver b,long inTimeout) {
final SlnDriver browser=b;
final long NO_LOADING_TIMEOUT = inTimeout;
class HasCondition implements ExpectedCondition<Boolean> {
#Override
public Boolean apply(WebDriver d) {
Boolean expected=false;
WebElement e = browser.findElement(By.xpath("blabla"));
if (e.getText().contains("TextYouWant")) {
expected= true;
break;
}
}
return expected;
}
}
}
for (;;) {
try {
new WebDriverWait(browser, NO_LOADING_TIMEOUT).until(new HasCondition());
} catch (TimeoutException e) {
return;
}
}
}