2012-07-18 102 views
10

有沒有辦法讓webDriverWait等待多個元素之一出現,並根據哪個元素出現相應的行爲?webdriver等待多個元素之一出現

此刻我在一個try循環中做了一個WebDriverWait,如果發生超時異常,我運行等待其他元素出現的替代代碼。這看起來很笨拙。有沒有更好的辦法?這裏是我的(笨拙)代碼:

try: 
    self.waitForElement("//a[contains(text(), '%s')]" % mime) 
    do stuff .... 
except TimeoutException: 
    self.waitForElement("//li[contains(text(), 'That file already exists')]") 
    do other stuff ... 

它涉及到等待一個完整的10單位爲秒,查看是否該文件已經存在系統上的消息之前。

功能waitForElement只是做了一些WebDriverWait呼叫,像這樣:

def waitForElement(self, xPathLocator, untilElementAppears=True): 
    self.log.debug("Waiting for element located by:\n%s\nwhen untilElementAppears is set to %s" % (xPathLocator,untilElementAppears)) 
    if untilElementAppears: 
     if xPathLocator.startswith("//title"): 
      WebDriverWait(self.driver, 10).until(lambda driver : self.driver.find_element_by_xpath(xPathLocator)) 
     else: 
      WebDriverWait(self.driver, 10).until(lambda driver : self.driver.find_element_by_xpath(xPathLocator).is_displayed()) 
    else: 
     WebDriverWait(self.driver, 10).until(lambda driver : len(self.driver.find_elements_by_xpath(xPathLocator))==0) 

任何人有任何建議,以更有效的方式做到這一點?

回答

7

創建一個函數,地圖上的標識符來XPath查詢並返回被匹配的標識符。

def wait_for_one(self, elements): 
    self.waitForElement("|".join(elements.values()) 
    for (key, value) in elements.iteritems(): 
     try: 
      self.driver.find_element_by_xpath(value) 
     except NoSuchElementException: 
      pass 
     else: 
      return key 

def othermethod(self): 

    found = self.wait_for_one({ 
     "mime": "//a[contains(text(), '%s')]", 
     "exists_error": "//li[contains(text(), 'That file already exists')]" 
    }) 

    if found == 'mime': 
     do stuff ... 
    elif found == 'exists_error': 
     do other stuff ... 
+0

謝謝。這會工作。 – amadain 2012-07-27 06:41:54

1

類似的東西:

def wait_for_one(self, xpath0, xpath1): 
    self.waitForElement("%s|%s" % (xpath0, xpath1)) 
    return int(self.selenium.is_element_present(xpath1)) 
+0

is_element_present是一個硒rc方法。這裏主要的是確定哪個'或語句'路徑被採用,以便返回的值可以告訴哪個代碼運行 – amadain 2012-07-24 11:36:19