A
A
Alexander Krasnov2015-11-20 17:59:27
Python
Alexander Krasnov, 2015-11-20 17:59:27

Why is StaleElementReferenceException thrown?

Good afternoon!
There are several tests for the same form that use the following code:

def select_drop_down(context, text, id):
WebDriverWait(context.browser, TIME_FOR_WAIT).until(
    EC.element_to_be_clickable((By.XPATH, '//div[@id = "%s"]/a' % id))
)
element = context.browser.find_element_by_xpath('//div[@id = "%s"]/a' % id)
scroll_element_into_view(context.browser, element)
context.browser.find_element_by_xpath('//div[@id = "%s"]/a' % id).click()
WebDriverWait(context.browser, TIME_FOR_WAIT).until(
    EC.presence_of_element_located((By.XPATH, "//*[@id='select2-drop']/div/input"))
)
context.browser.find_element_by_xpath("//*[@id='select2-drop']/div/input").send_keys(text)
WebDriverWait(context.browser, TIME_FOR_WAIT).until(
    EC.visibility_of_element_located((By.XPATH, '//*/li//*[contains(text(), "%s")]' % text))
)
context.browser.find_element_by_xpath('//*/li//*[contains(text(), "%s")]' % text).click()

The code selects an item from the drop down list.
In some tests it works, in others it doesn't.
Moreover, if you run tests in which the code does not work separately, the tests pass.
Problematic place:
context.browser.find_element_by_xpath("//*[@id='select2-drop']/div/input").send_keys(text)
WebDriverWait(context.browser, TIME_FOR_WAIT).until(
EC.visibility_of_element_located((By.XPATH, '//*/li//*[contains(text(), "%s")]' % text))

This is where an error sometimes occurs -- StaleElementReferenceException: Message: Element not found in the cache.
Why might this be happening?
Thank you.
PS Used by firefox 24

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Talik, 2017-01-10
@Pompeius_Magnus

I can only assume that at the moment of waiting for visibility (By.XPATH, '//*/li//*[contains(text(), "%s")]' % text) the element itself changes, because once the element is found, it goes out. Accordingly, during the next visibility check, the web driver simply no longer finds the element by the previously found reference to the object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question