Daniel Tkachenko
Daniel Tkachenko

Reputation: 7

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page

driver.get("https://www.zacks.com/")

driver.find_element_by_xpath("//*[@id='search-q']")

i am trying to find search box on zacks website with selenium but I am getting StaleElementReferenceException

Upvotes: 0

Views: 97

Answers (2)

Jannat Saikat
Jannat Saikat

Reputation: 1

Maybe you're trying to find while the page and this exact search box are loading. Try to implement wait mechanism for this element, smth like that:

WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));

Upvotes: 0

Arakis
Arakis

Reputation: 899

The reason why you're getting this error is simply, the element has been removed from the DOM. There are several reasons for this:

  • The page itself is destroying/recreating the element on the fly, maybe even rapidly.
  • Parts of the page have been updated (replaced), but you're still having and old reference.
  • You navigate to a new page but holding an old reference.

To avoid this, try to keep the element reference as short as possible. If the content is rapidly changing, make the operation directly without the round trip to the client, via javascript:

driver.executeScript("document.getElementById('serach-q').click();");

Upvotes: 1

Related Questions