Debugging StaleElementReference exception - Selenium WebDriver - java

I am in some kind of situation here.
I have a function editNewUser().
public void editNewUser() throws Exception
{
driver.findElement(adminModuleDD).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(searchRes));
List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(uNames));
for(WebElement el : elements)
{
if(el.getText().equals(UserName))
{
el.click();
wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
driver.findElement(editUser).click();
WebElement status_Dropdown = driver.findElement(By.xpath("//select[#id='systemUser_status']"));
Select status = new Select(status_Dropdown);
status.selectByVisibleText("Enabled");
}
}
}
The UserName is a public string variable that gets value in another function, during creation of user.
In this script, I am navigating to a page that contains list of users, I am storing all user names in List 'elements' and then iterating over each element in the list whose text matches with user name.
Now, in my test_run script, I have some other methods calling after editNewUser().
The thing happens is, this method executes the following commands in if block.
if(el.getText().equals(UserName))
{
el.click();
wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
driver.findElement(editUser).click();
WebElement status_Dropdown = driver.findElement(By.xpath("//select[#id='systemUser_status']"));
Select status = new Select(status_Dropdown);
status.selectByVisibleText("Enabled");
}
But as soon as next method is called, it stops the execution and throws org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Stack Trace refers to the line if(el.getText().equals(UserName)).
Can you tell me why am I receiving this exception, event though the commands inside if block are executed.

The error message is telling you the problem. The page has changed once you edit the first "el" in your for loop, the page has been updated, so Selenium has lost track of the remaining elements in the "elements" list.
You'll need to find another way to track the elements that you are looping through. a technique that I've used in the past is create a custom object to represent the items, in your case perhaps "User". that object is then smart enough that it can re-find itself on the page.

Related

Selenium error: no such element: Unable to locate element on .isDisplayed() method

I have an if statement below which is getting me an issue. If certain selections are made in a different dropdown, the page displays a second dropdown and a check box. The below code works as expected when a selection is made that causes those two elements to display but it doesn't if a selection is made that doesn't make them display. I get the no such element: Unable to locate element error. At first I thought it was returning true either way but the issue is it's crashing because. I even added a check at trying to assign the value to a booolean but still get the same error.
boolean dropdown = driver.findElement(By.id("DROPDOWN")).isDisplayed(); gets the same error.
if(driver.findElement(By.id("DROPDOWN")).isDisplayed()){
driver.findElement(By.id("DROPDOWN")).click();
driver.findElement(By.xpath("Choice in Drop DOWN)).click();
driver.findElement(By.id("CheckBox")).click();
}
findElement method will throw this hard exception - No such element if the element is not found. Just include Exception Handling for No Such Element and your logic should work just fine.
try{
if(driver.findElement(By.id("DROPDOWN")).isDisplayed()){
driver.findElement(By.id("DROPDOWN")).click();
driver.findElement(By.xpath("Choice in Drop DOWN)).click();
driver.findElement(By.id("CheckBox")).click();
}
catch (NoSuchElementException e)
{
// I believe you dont have to do anything here. May be a console log will do.
}
The following answers explain how to handle checking an element exists and handle the exception by wrapping in a custom method.
How to check if Element exists in c# Selenium drivers
I would also recommend re-writing your code as the following to avoid duplication and avoid xpath selectors. Using findElement twice for in the same context is not necessary just create a variable.
var dropdown = driver.findElement(By.id("DROPDOWN"));
if (dropdown.Displayed())
{
var selectElement = new SelectElement(dropdown);
selectElement.SelectByValue("valuehere");
}
If you are using the text rather than the value in the select box you can use SelectByText("texthere"); instead of SelectByValue.
isDisplayed() will work if the element is present in the DOM, followed by the style attribute :- display should not be false or none.
If prior action is a selection which led both the element to be displayed, it means the element is in the DOM but that wont be visible. So checking the visibility condition would return u false.
Try waiting for the element to get visible and perform the check operation on it which would reduce the sync latency.
WebDriverWait wait = new WebDriverWait(WebDriverRunner.getWebDriver(),5);
wait.until(ExpectedConditions.visibilityOfElementLocated("By Locator"));
if (dropdown.isDisplayed())
`````````// If the dropdown is tagged with <Select> tag
``````````` Select dropDown = new Select(dropdown);
```````````dropDown .selectByValue("value);
```````` // Else fetch the dropdown list item and store it in a list and iterate through and perform the desired action
```````````List<WebElement> dropDownList = new ArrayList<Webelements>;
```````````dropDownList.forEach(element -> {
```````````if(element.getText().equals("value")){
``````` ````element.click();
``````````` }
``````````` });
```````````driver.findElement(By.id("CheckBox")).click();
}

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?
The error message means it cannot find the element.
Few things,
Do you have the right selector for that element?
Does the webpage use JQuery or AngularJS? If so, you need to wait for them to load
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.
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
This is solution:
#FindAll(#FindBy(xpath = ""))
List<WebElement> buttonelements
if(!buttonelements.isEmpty()){
'code here'
}
Cause of a problem:
Using FindBy and method isDisplayed() throws NoSuchElementException if no matching elements are found.
Using FindAll and method isEmpty() don't throw any suchexception, it will return empty list.

Selenium made a sendKeys for two fields instead of one for some reason

I made a pretty simple selenium test, where I want to open web page, clear field value, start entering text for this field, select first value from the hint drop down.
Web site is aviasales.com (I just found some site with a lot of controls, this is not an advertisement)
I did
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).clear();
and it was working perfectly, I also checked via console that this is the only one object on a page like:
document.getElementById('flights-origin-prepop-whitelabel_en')
So, in next line I'm sending value:
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).sendKeys("LAX");
but it send LAX value for both "flights-origin-prepop-whitelabel_en" and "flights-destination-prepop-whitelabel_en" for some reason, then i tried
DriverFactory.getDriver().findElement(By.id("//input[#id='flights-destination-prepop-whitelabel_en'][#placeholder='Destination']")).sendKeys(destinationAirport);
but I got the same result:
What could be a reason and how to fix this?
Thank you!
Yep... there's some weird behavior going on there. The site is copying whatever is entered into the first field into the second for reason I don't understand. I gave up trying to understand it and found a way around it.
Whenever I write code that I know I'm going to reuse, I put them into functions. Here's the script code
driver.navigate().to(url);
setOrigin("LAX");
setDestination("DFW");
...and since you are likely to use these repeatedly, the support functions.
public static void setOrigin(String origin)
{
WebElement e = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(origin);
e.sendKeys(Keys.TAB);
}
public static void setDestination(String dest)
{
WebElement e = driver.findElement(By.id("flights-destination-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(dest);
e.sendKeys(Keys.TAB);
}
You can see the functions but basically I click in the field, clear the text (because usually there's something already in there), send the text, and then press to move out of the field and choose the default (first choice).
The reason of your issue is the ORIGIN and DESTINATION inputbox binded keyboard event which used to supply an autocomplete list according to your typed characters.
The binded keyborad event breaks the normal sendKeys() functionality. I met similar case in my projects and questions on StackOverFlow.
I tried input 'GSO' into DESTINATION by sendKeys('GSO'), but I get 'GGSSOO' on page after the sendKeys() complete.
To resolve your problem, we can't use sendKeys(), we have to use executeScript() to set the value by javascript in backgroud. But executeScript() won't fire keyborad event so you won't get the autocomplete list. So we need find out a way to fire keyborady event after set value by javascript.
Below code snippet worked on chrome when i tested on aviasales.com:
private void inputAirport(WebElement targetEle, String city) {
String script = "arguments[0].value = arguments[1]";
// set value by javascript in background
((JavascriptExecutor) driver).executeScript(script, targetEle, city + "6");
// wait 1s
Thread.sleep(1000);
// press backspace key to delete the last character to fire keyborad event
targetEle.sendKeys(Keys.BACK_SPACE);
// wait 2s to wait autocomplete list pop-up
Thread.sleep(2000);
// choose the first item of autocomplete list
driver.findElement(By.cssSelector("ul.mewtwo-autocomplete-list > li:nth-child(1)")).click();
}
public void inputOrigin(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
return inputAirport(target, city);
}
public void inputDestination(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepopflights-destination-prepop-whitelabel_en"));
return inputAirport(target, city);
}

Webdriver, detect DOM changing and wait for it

I am using Webdriver in Java and I encountered an issue repeatedly that I can't find a proper solution yet.
It is to do with doing actions on a page that will cause this page DOM to change (for example, Javascript lightbox), then my JUnit test is expecting new elements after the DOM change but my test is getting the old DOM element.
To give you an example, I have a scenario as below.
First of all click “Add item” button in the below image and the light box appears:
Then fill in all the item details and click "Add & Close". You will see the screen below:
Notice that now there is an info message Your item ... has been added.
Now I put keywords in the Search text box and hit enter and the info message will be changed to below:
In my JUnit test, the flow is like below:
....
itemDetailsPage.clickAddAndClose();
itemDetailsPage.searchItemBy("Electricity");
assertEquals("Your search for 'electricity' returned 2 results.",
itemDetailsPage.getInfoMsg());
....
Now this test is not very robust, because if the network is slow, most of the times, getInfoMsg() will return the previous info message Your item ... has been added instead of the latest info message, which causes the test to fail. Just a side note that these two info message have share the same html element id.
The solution I am trying to implement here are:
add explicit wait in clickAddAndClose()
So it looks something like:
public void clickAddAndClose() {
...
clickWhenReady(driver, By.id(addAndCloseButtonId));
...
waitForElementByLocator(driver,By.id(itemInfoMsgId),10);
}
The second wait proves to be useless because, itemInfoMsgId already exist when the user added the item from the add item lightbox.
add waitForPageLoaded() method at the end of clickAddAndClose() to try to wait for the page to finish reloading. The generic method for waitForPageLoaded() below:
public void waitForPageLoaded(WebDriver driver) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState").equals("complete");
}
};
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
try {
wait.until(expectation);
} catch (Throwable error) {
assertFalse("Timeout waiting for Page Load Request to complete.",
true);
}
}
I am expect at the end of clickAddAndClose(), it will see this page is still being updated so it will wait until the info message has been updated. But this does not seem to work either.
That leaves me to the last choice will is to add a thread sleep at the end of clickAddAndClose(). I want to avoid using it.
Is there a generic way of solving this kind of problem? How do I detect that the page DOM is still changing and tell Webdriver to wait until it finishes refreshing?
Waiting for the page to be loaded won't work if (as it seems to be the case) your page is being modified by AJAX operations.
Instead of waiting for the page to load, wait for the condition you are testing to become true. This way, you give the AJAX operation time to execute and if your there is a problem you will get an error when the time out occurs.
I usually use the Python bindings for Selenium and it has been quite a while since I wrote Java code but I believe it would look something like this, with X being replaced with a type appropriate for the itemDetailsPage object:
new FluentWait<X>(itemDetailsPage)
.until(new Function<X, Boolean>() {
public Boolean apply(X itemDetailsPage) {
return "Your search for 'electricity' returned 2 results." == itemDetailsPage.getInfoMsg();
};
});
Seems like you need to wait until ajax has finished its job. In a similar situation I've used a method similar to waitForJQueryProcessing described here. Take a look, it might help.

Selenium : Handling Loading screens obscuring the web elements. (Java)

I'm writing an automated test case for a web page. Here's my scenario.
I have to click and type on various web elements in an html form. But, sometimes while typing on a text field, an ajax loading image appears , fogging all elements i want to interact with. So, I'm using web-driver wait before clicking on the actual elements like below,
WebdriverWait innerwait=new WebDriverWait(driver,30);
innerwait.until(ExpectedConditions.elementToBeClickable(By.xpath(fieldID)));
driver.findelement(By.xpath(fieldID)).click();
But the wait function returns the element even if it is fogged by another image and is not clickable. But the click() throws an exception as
Element is not clickable at point (586.5, 278).
Other element would receive the click: <div>Loading image</div>
Do I have to check every time if the loading image appeared before interacting with any elements?.(I can't predict when the loading image will appear and fog all elements.)
Is there any efficient way to handle this?
Currently I'm using the following function to wait till the loading image disappears,
public void wait_for_ajax_loading() throws Exception
{
try{
Thread.sleep(2000);
if(selenium.isElementPresent("id=loadingPanel"))
while(selenium.isElementPresent("id=loadingPanel")&&selenium.isVisible("id=loadingPanel"))//wait till the loading screen disappears
{
Thread.sleep(2000);
System.out.println("Loading....");
}}
catch(Exception e){
Logger.logPrint("Exception in wait_for_ajax_loading() "+e);
Logger.failedReport(report, e);
driver.quit();
System.exit(0);
}
}
But I don't know exactly when to call the above function, calling it at a wrong time will fail. Is there any efficient way to check if an element is actually clickable? or the loading image is present?
Thanks..
Given the circumstances that you describe, you are forced to verify one of two conditions:
Is the element that you want to click clickable?
Is the reason that blocks the clicks still present?
Normally, if the WebDriver is able to find the element and it is visible, then it is clickable too. Knowing the posible reasons that might block it, I would rather choose to verify those reasons. Besides, it would be more expressive in the test code: you clearly see what you are waiting for, what you are checking before clicking the element, instead of checking the "clickability" with no visible reason for it. I think it gives one (who reads the test) a better understanding of what is (or could be) actually going on.
Try using this method to check that the loading image is not present:
// suppose this is your WebDriver instance
WebDriver yourDriver = new RemoteWebDriver(your_hub_url, your_desired_capabilities);
......
// elementId would be 'loadingPanel'
boolean isElementNotDisplayed(final String elementId, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
WebElement element = webDriver.findElement(By.id(elementId));
return !element.isDisplayed();
}
};
Wait w = new WebDriverWait(yourDriver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
// if it gets here it is because the element is still displayed after timeoutInSeconds
// insert code most suitable for you
}
return true;
}
Perhaps you will have to adjust it a bit to your code (e.g. finding the element once when the page loads and only checking if it is displayed).
If you are not sure when exactly the loading image comes up (though I suppose you do), you should call this method before every click on elements that would become "unclickable" due to the loading image. If the loading image is present, the method will return true as soon as it disappears; if it doesn't disappear within 'timeoutInSeconds' amount of time, the method will do what you choose (e.g. throw an exception with specific message).
You could wrap it together like:
void clickSkippingLoadingPanel(final WebElement elementToClick) {
if (isElementNotDisplayed('loadingPanel', 10)) {
elementToClick.click();
}
}
Hope it helps.

Categories