1

I used this code for Clearing Text Field by Id (using Selenium with python 2.7):

from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome():
browser.get('https://www.google.com')
search = browser.find_element_by_id('lst-ib')
search.send_keys('Python 2')
search.send_keys(Keys.RETURN)
time.sleep(6)
search.clear()
time.sleep(2)
browser.close()

It gave me the error:

StaleElementReferenceException Traceback (most recent call last) in () StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=65.0.3325.181) (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64)

Does anyone know how to fix this

1

1 Answer 1

3

Once you do search.send_keys(Keys.RETURN) new page is loaded and search is no more accessible. You just need to re-define this variable

from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome():
browser.get('https://www.google.com')
search = browser.find_element_by_id('lst-ib')
search.send_keys('Python 2')
search.send_keys(Keys.RETURN)
time.sleep(6)
search = browser.find_element_by_id('lst-ib')
search.clear()
time.sleep(2)
browser.close()

Also note that using time.sleep() is a bad practice. You should look towards Implicit/Explicit waits

Sign up to request clarification or add additional context in comments.

5 Comments

Or a better way would be clicking on the element inside a loop. darrellgrainger.blogspot.in/2012/06/staleelementexception.html
clicking on the element? Do you see any clicking in code?
Keys.Enter (passing the keyboard keys ) is an alternative of finding an element and clicking on it !
The problem is that OP calls input field object after DOM updated. Can you elaborate how loop can solve this issue?
you can go through the provided website. That was my understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.