在自动执行某些测试时遇到了一些问题 - 主要是WebDriverException,点击将被另一个对象捕获。我可以通过使用webdriverwait来解决问题,使元素消失 - 这是一个在模态中显示的滑动成功消息,但异常消息让我思考;是否可以捕获异常,解析文本并提取对象的某些可识别信息,然后在webdriverwait上使用该方法,而不是使用显式等待?
例如,如果我这样做:
self.wait_for_success_modal_to_disappear(context)
self.element_is_clickable(context, mark_as_shipped).click()
它会工作,但如果我注释掉等待方法,它将失败,并显示错误消息:
WebDriverException: Message: unknown error: Element is not clickable at
point (x, y). Other element would receive the click: <div class="success-modal">...</div>
我正在考虑的是修改element_is_clickable
方法以在基于异常文本的可重用方法中包含异常处理,如下所示:
def element_is_clickable(self, context, locator):
try:
WebDriverWait(context.driver, 15).until(
EC.visibility_of_element_located(locator)
)
WebDriverWait(context.driver, 15).until(
EC.element_to_be_clickable(locator)
)
return context.driver.find_element(*locator)
except WebDriverException:
error_message = repr(traceback.print_exc())
modal_class_name = <<method to grab everything between the quotation marks>>
WebDriverWait(context.driver, 15).until(
EC.invisibility_of_element_located((By.CLASS_NAME, modal_class_name))
)
WebDriverWait(context.driver, 15).until(
EC.visibility_of_element_located(locator)
)
WebDriverWait(context.driver, 15).until(
EC.element_to_be_clickable(locator)
)
return context.driver.find_element(*locator)
现在,我知道这不是处理这个的正确方法,因为错误是在click()上没有识别元素,但我最感兴趣的是捕获和解析异常消息的可能性以有用的方式使用该数据。这有可能吗?
答案 0 :(得分:0)
您可以等到可以捕获点击的对象消失,条件为until_not
import re
try:
# click already defined element, e.g. button
element.click()
except WebDriverException as e:
# in case of captured click parse exception for this div locator
xpath = '//div[@%s]' % re.search('class="\w+"', e.args[0]).group() # this is just a simple example of how to handle e.args[0] (exception message string) with regular expressions- you can handle it as you want to
# wait until modal disappear
WebDriverWait(driver, 15).until_not(EC.visibility_of_element_located((By.XPATH, xpath)))
# click again
element.click()