This Exception occurs when driver is trying to perform action on the element which is no longer exists or not valid.
WebElement ele = driver.findElement(By.id("sample"));
// Before clicking some thing happened and DOM has changed due to page refresh, or element is removed and re-added
ele.click();
Now at this point, the element which you're clicking is no longer valid.
so it throws up its hands and gives control to user, who as the test/app author should know exactly what may or may not happen.
In order overcome this, we need to explicitly wait until the DOM is in a state where we are sure that DOM won't change.
For example, using a WebDriverWait to wait for a specific element to exist:
/ times out after 10 seconds
WebDriverWait wait = new WebDriverWait(driver, 10);
// while the following loop runs, the DOM changes -
// page refreshed, or element removed and re-added
wait.until(elementIdentified(By.id("element")));
// now we're good - let's click the element
driver.findElement(By.id("sample")).click();
private static Function<WebDriver,WebElement> elementIdentified(final By locator) {
return new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
You can also user implicit waits, in which Webdriver will check for the element to become present until the specified timeout:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
- ‹ Mouse Hover Actions in Selenium Webdriver
- Difference between Webdriver get() and Webdriver navigate() ›
Comments
Webdriver with PhantomJSDriver
Hi ,
I trying to integrate webdriver with PhantomJSDriver for headless browser automation but its not working properly. Getting error.
FAILED CONFIGURATION: @BeforeMethod setUp
java.lang.IllegalStateException: The path to the driver executable must be set by the phantomjs.binary.path capability/system property/PATH variable; for more information, see https://github.com/ariya/phantomjs/wiki. The latest version can be downloaded from http://phantomjs.org/download.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:177)
at org.openqa.selenium.phantomjs.PhantomJSDriverService.findPhantomJS(PhantomJSDriverService.java:237)
at org.openqa.selenium.phantomjs.PhantomJSDriverService.createDefaultService(PhantomJSDriverService.java:182)
Your help much appreciated.
Regards,
Dhanapalan
test
I think you need to add the path of your phantom to your class path. check how to configure webdriver. You need to open the environmental variable and update the path.
solution for StaleElementException
Use ' try -- catch' in for loop for Java, ' try -- except' in for loop for Python
Add new comment