Selenium配合Gauge使用时WebDriverWait返回dict而非网页元素如何解决?
问题原因
出现该问题的核心是Gauge框架封装的Selenium驱动在调用预期条件方法时,直接返回了WebDriver JSON Wire协议的原始响应字典,没有自动转换成Selenium标准的WebElement对象,你拿到的{'ELEMENT': '0.8884832448581164-1'}就是元素的唯一标识引用。
解决方案
- 方案1:手动将返回的字典转为标准WebElement对象(最快捷有效)
你只需要在wait_for_elem方法中增加一步类型判断和转换逻辑即可,修改后的完整代码如下:
from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.remote.webelement import WebElement from step_impl.mixins.exception import MixinException class MixinSelector(MixinException): def __init__(self, driver=None): super(MixinSelector, self).__init__(driver) self.wait_for_element_time = 60 def wait_for_elem(self, by, locator_string): try: result = WebDriverWait(self.driver,self.wait_for_element_time)\ .until(EC.presence_of_element_located((by, locator_string))) # 新增转换逻辑 if isinstance(result, dict) and 'ELEMENT' in result: element = WebElement(self.driver, result['ELEMENT']) else: element = result print(element) print(type(element)) return element except TimeoutException: self.fail_test('failed') except: raise
转换后的WebElement就可以直接调用click()、text、send_keys()等所有标准Selenium元素方法。
方案2:检查driver实例来源
如果你传入的是自己初始化的原生Selenium WebDriver实例,需要确认已经和Gauge的执行上下文正确绑定;如果是使用Gauge官方提供的Selenium驱动实例,直接使用方案1的转换逻辑即可适配。验证方法
你可以先执行以下代码确认driver本身的返回类型:
elem = self.driver.find_element(By.CSS_SELECTOR, '#baseWebLayoutContainerID') print(type(elem))
如果返回的还是dict类型,说明驱动本身的封装就没有做转换,方案1的逻辑可以全局适配所有元素获取场景。
内容的提问来源于stack exchange,提问作者Pablo R.R.
相关产品推荐
相关产品推荐

