webdriver等待多个元素之一出现

时间:2012-07-18 11:09:19

标签: python selenium webdriver selenium-webdriver wait

有没有办法让webDriverWait等待多个元素中的一个出现,并根据出现的元素进行相应的操作?

目前我在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)

有人建议以更有效的方式完成这项工作吗?

2 个答案:

答案 0 :(得分:8)

创建一个函数,该函数将标识符映射到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 ...

答案 1 :(得分:1)

类似的东西:

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