0

If Selenium throws a StaleElementReferenceException it is usually (?) because the state of web page (DOM) Selenium "owns" has changed due to outside interference but I started to get it when I added frameToBeAvailableAndSwitchToIt before a switch statement. My code:

driver.findElement(By.xpath(xpDownArrow)).click();
WebElement iframeElement = driver.findElement(By.xpath(xpIframe));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath(xpIframe)));
driver.switchTo().frame(iframeElement);

Originally my code consisted just of line 1, 2 and 4, which worked most of the time but failed 10-20 % of the executions, and I therefore added line 2 but now I get the StaleElementReferenceException everytime this code executes. I don't get that. Why would line 3 change the DOM? Isn't this the recommended way to perform a switch?

d-b
  • 695
  • 3
  • 14
  • 43

2 Answers2

1

Instead of those smaller redundant steps you can switch to the desired <iframe> inducing WebDriverWait using an optimally as follows:

new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("xpIframe")));

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

With line 3

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath(xpIframe)));

you've already switched to iframe. So line 4 is not needed- it just trying to perform switching to the same frame. Try to remove it (line 2 is also redundant)

JaSON
  • 4,843
  • 2
  • 8
  • 15