【问题标题】:Check for a stale element using selenium 2?使用 selenium 2 检查过时的元素?
【发布时间】:2017-11-10 05:36:45
【问题描述】:

使用 selenium 2,有没有办法测试元素是否过时?

假设我启动了从一页到另一页的转换 (A -> B)。然后我选择元素 X 并对其进行测试。假设元素 X 存在于 A 和 B 上。

在页面转换发生之前,会间歇性地从 A 中选择 X,直到转到 B 之后才进行测试,从而引发 StaleElementReferenceException。很容易检查这种情况:

try:
  visit_B()
  element = driver.find_element_by_id('X')  # Whoops, we're still on A
  element.click() 
except StaleElementReferenceException:
  element = driver.find_element_by_id('X')  # Now we're on B
  element.click()

但我宁愿这样做:

element = driver.find_element_by_id('X') # Get the elment on A
visit_B()
WebDriverWait(element, 2).until(lambda element: is_stale(element))
element = driver.find_element_by_id('X') # Get element on B

【问题讨论】:

    标签: python selenium-webdriver


    【解决方案1】:

    我不知道你在那里使用什么语言,但你需要解决这个问题的基本思路是:

    boolean found = false
    set implicit wait to 5 seconds
    loop while not found 
    try
      element.click()
      found = true
    catch StaleElementReferenceException
      print message
      found = false
      wait a few seconds
    end loop
    set implicit wait back to default
    

    注意:当然,大多数人不这样做。大多数时候人们使用 ExpectedConditions 类,但是在需要更好地处理异常的情况下 这种方法(我在上面说过)可能会更好。

    【讨论】:

      【解决方案2】:

      在 Ruby 中,

      $default_implicit_wait_timeout = 10 #seconds
      
      def element_stale?(element)
        stale = nil  # scope a boolean to return the staleness
      
        # set implicit wait to zero so the method does not slow your script
        $driver.manage.timeouts.implicit_wait = 0
      
        begin ## 'begin' is Ruby's try
          element.click
          stale = false
        rescue Selenium::WebDriver::Error::StaleElementReferenceError
          stale = true
        end
      
        # reset the implicit wait timeout to its previous value
        $driver.manage.timeouts.implicit_wait = $default_implicit_wait_timeout
      
        return stale
      end
      

      上面的代码是ExpectedConditions提供的stalenessOf方法的Ruby翻译。类似的代码可以用 Python 或 Selenium 支持的任何其他语言编写,然后从 WebDriverWait 块调用以等待元素变得陈旧。

      【讨论】:

        猜你喜欢
        • 2013-10-30
        • 1970-01-01
        • 2020-05-02
        • 2019-10-04
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        相关资源
        最近更新 更多