11

有没有办法让 awebDriverWait等待多个元素中的一个出现并根据出现的元素采取相应的行动?

目前我WebDriverWait在 try 循环中执行一个操作,如果发生超时异常,我将运行等待其他元素出现的替代代码。这似乎很笨拙。有没有更好的办法?这是我的(笨拙的)代码:

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)

有人有任何建议以更有效的方式完成此任务吗?

4

2 回答 2

9

创建一个函数,将标识符映射到 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 ...
于 2012-07-26T23:00:15.543 回答
1

像这样的东西:

def wait_for_one(self, xpath0, xpath1):
    self.waitForElement("%s|%s" % (xpath0, xpath1))
    return int(self.selenium.is_element_present(xpath1))
于 2012-07-22T09:26:32.563 回答