Check for a stale element using selenium 2?

前端 未结 2 459
温柔的废话
温柔的废话 2021-01-13 09:03

Using selenium 2, is there a way to test if an element is stale?

Suppose I initiate a transition from one page to another (A -> B). I then select element X and test

2条回答
  •  清酒与你
    2021-01-13 09:12

    In 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
    

    The code above is a Ruby translation of the stalenessOf method provided by ExpectedConditions. Similar code could be written in Python or any other language Selenium supports, and then called from a WebDriverWait block to wait until the element becomes stale.

提交回复
热议问题