1

I'm new to python coding. And I'm trying to play around with python and Selenium in chrome. And I have this code where I'm trying to move a webpage up and down. But it isn't working.

body_elem = browser.find_element_by_tag_name('body')

for __ in range(3):
    body_elem.send_keys(Keys.END)
    sleep(2)
    body_elem.send_keys(Keys.HOME)
    sleep(2)

All I get is this long error message:

Traceback (most recent call last):
  File "selenium_test.py", line 34, in <module>
    body_elem.send_keys(Keys.HOME)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys
    'value': keys_to_typing(value)})
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 628, in _execute
    return self._parent.execute(command, params)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

Anybody got an idea of whats is wrong?

1 Answer 1

1

This is most likely because of the fact that the DOM tree or the body element signature itself changed after the first "down" move. One straightforward way to approach the problem would be to "re-find" the element constantly:

for _ in range(3):
    browser.find_element_by_tag_name('body').send_keys(Keys.END)
    sleep(2)
    browser.find_element_by_tag_name('body').send_keys(Keys.HOME)
    sleep(2)
Sign up to request clarification or add additional context in comments.

2 Comments

Great that works. But isn't that the same as using body_elem = browser.find_element_by_tag_name('body')?
@user3403590 glad it worked. No, every time you issue "find element" command - there is a JSON over HTTP request sent to the "webdriver" which allows us to "refresh" the body web element instance we are working with in the Python code..

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.