Reputation: 1
I am using selenium 3.9.1 and java to automate testing of a web application. The web application has some dynamic content based on pressing of a button for example. The page refreshes whenever this button is clicked. A java script runs on button click and updates the DOM I think. At this time, when I try to access the button (which is visible on the page), I get a staleElementReferenceException.
Does Selenium automatically reload the DOM once it is changed? I am relatively new to selenium. I have researched into this and I have tried to refresh the page using driver.navigate().Refresh() to try to see whether this will solve the problem. It does not solve the issue.
Any pointers will be deeply appreciated.
Upvotes: 0
Views: 185
Reputation: 842
You could do something like this:
public void SaveAndAgainClick() throws Exception{
try{
clicksaveButton(); //method to click save button
WebElement someValue = driver.findElement(By.xpath("(//input[@name='someValue'])[1]"));
someValue.click();
}catch (StaleElementException e){
WebElement someValue = driver.findElement(By.xpath("(//input[@name='someValue'])[1]");
someValue.click();
}
}
If findElement gets staleElementError while looking for (//input[@name='someValue'])[1]
then it will again try one more time in the catch block and most certainly find the element and clicks on it. Your test will pass if you follow this approach.
Upvotes: 1
Reputation: 193058
Here are the answers to your questions :
Consider the following HTML :
<input value="Click me" onclick="alert('Click!')" type="button">
In the given HTML as per the onclick
attribute of this element, if you invoke click()
method on the WebElement, an alert would be generated. Similarly the onclick
attribute may invoke a JavaScript or Ajax which may bring-in/phase-out new/old elements from the HTML DOM
driver.navigate().refresh()
wouldn't be a optimum solution as it may not invoke the intended JavaScript or Ajax properly. Hence the intended WebElement may not be interactive in a optimum way.Upvotes: 0
Reputation: 99
If the page is refreshed all the items in the DOM are now stale. What this means is that all items found before the button press will have to be found again. Any attempts to use those items will more than likely be treated with a stale element exception.
However, if the button click mearilly affects items on the page without having to ask the webserver to give you a new page you could interact with the old items.
Upvotes: 1
Reputation: 3665
Since the page has been refreshed, the button reference you have is to the button on the old page that no longer exists.
I'd say you need to get a new reference to the button on the refreshed page (eg call FindElementById).
Upvotes: 1