2012-07-18 26 views
10

Có cách nào để nhận một số webDriverWait để chờ một trong số các yếu tố xuất hiện và hành động tương ứng dựa trên yếu tố nào xuất hiện không?Trình quản trị trang web chờ một trong nhiều yếu tố xuất hiện

Hiện tại tôi làm WebDriverWait trong vòng lặp thử và nếu xảy ra lỗi thời gian chờ, tôi chạy mã thay thế chờ phần tử khác xuất hiện. Điều này có vẻ vụng về. Có cách nào tốt hơn? Đây là mã của tôi (vụng về):

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

Nó liên quan đến việc chờ đợi toàn bộ 10 giây trước khi có vẻ như thông báo tệp đã tồn tại trên hệ thống.

Chức năng waitForElement chỉ cần một số WebDriverWait cuộc gọi như vậy:

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) 

Bất kỳ ai bị bất cứ đề nghị để thực hiện điều này một cách hiệu quả hơn?

Trả lời

7

Tạo một hàm mang theo bản đồ về định danh để XPath truy vấn và trả về nhận dạng đó là lần xuất.

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

cảm ơn. Điều đó sẽ hiệu quả. – amadain

1

Something như thế:

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 là một phương thức selenium rc. Điều chính ở đây là xác định đường dẫn 'hoặc câu lệnh' nào đã được thực hiện sao cho giá trị trả lại có thể cho biết mã nào để chạy – amadain

Các vấn đề liên quan