一尘不染

webdriver等待多个元素之一出现

selenium

是否有办法让a webDriverWait等待许多元素之一出现并根据哪个元素出现而采取相应的行动?

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

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


阅读 425

收藏
2020-06-26

共1个答案

一尘不染

创建一个将标识符映射到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 ...
2020-06-26