是否可以从 webdriver 异常文本中获取定位器?

Is it possible to grab a locator from webdriver exception text?

我 运行 在自动执行某些测试时遇到了一些问题 - 主要是 WebDriverException,点击将被不同的对象捕获。我可以通过使用 webdriverwait 让元素消失来解决这个问题——这是一个以模式显示的滑动成功消息,但异常消息让我开始思考;除了使用显式等待,是否可以捕获异常、解析文本并提取对象的一些可识别信息,然后在方法的 webdriverwait 中使用它?

例如,如果我这样做:

self.wait_for_success_modal_to_disappear(context)
self.element_is_clickable(context, mark_as_shipped).click()

它会工作,但如果我注释掉 wait 方法,它将失败并显示错误消息:

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() 上而不是在识别元素上,但我最感兴趣的是捕获和解析异常的可能性消息并以有用的方式使用该数据。这完全可能吗?

您可以等到可以捕获点击的对象消失,条件是 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()