webdriver等待多个元素之一出现 [英] webdriver wait for one of a multiple elements to appear
问题描述
有没有办法让webDriverWait
等待许多元素之一出现并根据出现的元素采取相应的行动?
Is there a way to get a webDriverWait
to wait for one of a number of elements to appear and to act accordingly based on which element appears?
此刻,我在try循环中执行了WebDriverWait
,如果发生超时异常,我将运行备用代码,等待其他元素出现.这看起来很笨拙.有没有更好的办法?这是我的代码(笨拙):
At the moment I do a WebDriverWait
within a try loop and if a timeout exception occurs I run the alternative code which waits for the other element to appear. This seems clumsy. Is there a better way? Here is my (clumsy) code:
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秒钟,然后才能查看系统上是否已存在该文件的消息.
It involves waiting an entire 10 seconds before it looks to see if the message that the file already exists on the system.
函数waitForElement
只是执行许多WebDriverWait
调用,如下所示:
The function waitForElement
just does a number of WebDriverWait
calls like so:
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)
有人有任何建议以更有效的方式实现这一目标吗?
Anybody got any suggestions to accomplish this in a more efficient way?
推荐答案
创建一个将标识符映射到xpath查询并返回匹配标识符的函数.
Create a function that takes a map of identifiers to xpath queries and returns the identifier that was matched.
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 ...
这篇关于webdriver等待多个元素之一出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!