Python selenium send_keys在chrome中不起作用

时间:2018-04-05 21:01:54

标签: python python-3.x selenium

我是python编码的新手。而我正试图在chrome中使用python和Selenium。我有这个代码,我试图上下移动一个网页。但它没有用。

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)

我得到的只是这个长错误信息:

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

任何人都知道什么是错的?

1 个答案:

答案 0 :(得分:1)

这很可能是因为 DOM树或body元素签名本身在第一个&#34; down&#34;之后发生了变化。移动。解决问题的一种直接方法是“重新找到问题”。元素不断:

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)