2017-05-05 114 views
3

我有一個元素的屬性「詠歎調」,當數據在搜索和完成時,從真變爲假。如何使用selenium Expected Conditions和Explicit Waits來等待20秒的默認時間,如果達到20秒並且屬性沒有從true更改爲false。拋出異常。我有以下,但它並沒有真正的工作使用硒webdriver等待元素的屬性來改變值

import selenium.webdriver.support.ui as ui 
from selenium.webdriver.support import expected_conditions as EC 

<div id="xxx" role="combobox" aria-busy="false" /div> 
class Ele: 
    def __init__(self, driver, locator) 
     self.wait = ui.WebDriverWait(driver, timeout=20) 

    def waitEle(self): 
     try: 
      e = self.driver.find_element_by_xpath('//div[@id='xxxx']') 
      self.wait.until(EC.element_selection_state_to_be((e.get_attribute('aria-busy'), 'true'))) 
     expect: 
      raise Exception('wait timeout') 

回答

2

預期的條件僅僅是一個調用,你可以將它定義爲一個簡單的函數:

def not_busy(driver): 
    try: 
     element = driver.find_element_by_id("xxx") 
    except NoSuchElementException: 
     return False 
    return element.get_attribute("aria-busy") == "false" 

self.wait.until(not_busy) 

有點更通用的和模塊化的,不過,將遵循內置預期時的風格,創造class with a overriden __call__() magic method

from selenium.webdriver.support import expected_conditions as EC 

class wait_for_the_attribute_value(object): 
    def __init__(self, locator, attribute, value): 
     self.locator = locator 
     self.attribute = attribute 
     self.value = value 

    def __call__(self, driver): 
     try: 
      element_attribute = EC._find_element(driver, self.locator).get_attribute(self.attribute) 
      return element_attribute == self.value 
     except StaleElementReferenceException: 
      return False 

用法:

self.wait.until(wait_for_the_attribute_value((By.ID, "xxx"), "aria-busy", "false")) 
1

另一種方法是涉及與定製定位檢查的屬性值,你不僅會檢查id也是aria-busy屬性值:

self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#xxx[aria-busy=false]")))