python - Selenium WebDriver - 处理 StaleElementReferenceException (Python)

标签 python selenium exception

我正在使用 Selenium 编写 Python 代码,该代码单击网页上的按钮。单击按钮后,按钮会变为其他内容。我的代码工作得很好,但 Selenium 将此误解为一个问题。我试图忽略异常并继续,但我尝试过的任何方法都不起作用。

from selenium.common.exceptions import StaleElementReferenceException

try:
    browser.find_element_by_xpath("//*[contains(text(), 'SomeButtonText')]").click()
except StaleElementReferenceException:
    pass

我可以做什么来忽略异常并继续前进?我的代码适用于我想要做的事情,但几秒钟后,抛出异常。

Message: Element not found in the cache - perhaps the page has changed since it was looked up

这是来自 Ubuntu 终端的极其困惑的信息:

File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 107, in get_attribute
    resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 454, in _execute
    return self._parent.execute(command, params)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
Stacktrace:
    at fxdriver.cache.getElementAt (resource://fxdriver/modules/web-element-cache.js:9351)
    at Utils.getElementAt (file:///tmp/tmp24d8CK/extensions/fxdriver@googlecode.com/components/command-processor.js:8978)
    at WebElement.getElementAttribute (file:///tmp/tmp24d8CK/extensions/fxdriver@googlecode.com/components/command-processor.js:12019)
    at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmp24d8CK/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
    at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmp24d8CK/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
    at DelayedCommand.prototype.execute/< (file:///tmp/tmp24d8CK/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)

最佳答案

我找到了问题的答案。

这里的代码:

try:
    browser.find_element_by_xpath("//*[contains(text(), 'SomeButtonText')]").click()
except StaleElementReferenceException:
    pass

在 for 循环结束时执行。我完全错过了这样一个事实:它返回到循环的开头,在那里我遇到了一个单独的问题,即过时的引用异常。

关于python - Selenium WebDriver - 处理 StaleElementReferenceException (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280723/

相关文章:

python - 将 iMacros 脚本集成到 python 中

python - 修改 Dijkstra 以进行计数

python - 如何在 Python 中比较两个 SQLite 数据集并搜索相似之处?

java - 如何用Java和Webdriver处理过大的页面对象?

python - Pandas 将 nan 替换为给定分组的平均值

java - 没有这样的元素 : Unable to locate element: exception coming in selenium

selenium - xpath:查找具有属性并且包含的​​元素?

java - 返回空指针异常但预期有 MovieListException?

c# - 委托(delegate) - 异常不会等到调用 EndInvoke()

java - GWT 奇怪的序列化异常