gpt4 book ai didi

Python、Selenium - 处理多个等待条件

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:06 25 4
gpt4 key购买 nike

我有一个名为 webdriver.py 的文件,它实现了 selenium.webdriver 库中的方法。有一个等待函数可以处理我需要的大多数情况:

def wait_for(self, func, target=None, timeout=None, **kwargs):
timeout = timeout or self.timeout
try:
return WebDriverWait(self, timeout).until(func)
except TimeoutException:
if not target:
raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
raise NoSuchElementException(target)

其中 func 是选择器。

问题是有时 DOM 元素会不可见,导致异常和测试失败。因此,我想扩展 wait_for 来等待元素变得可见。

类似于

def wait_for(self, func, target=None, timeout=None, **kwargs):
timeout = timeout or self.timeout
try:
return WebDriverWait(self, timeout).until(EC.element_to_be_clickable(func)).until(func)
except TimeoutException:
if not target:
raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
raise NoSuchElementException(target)

EC 是一个 selenium.driver.expected_conditions

这当然行不通 - 要么不支持 until().until() 语法..或者发生其他情况,例如 EC 不存在。

有什么想法吗?

最佳答案

您可以使用 EC.presence_of_element_ located 等待 DOM 中的元素可见,无需第二个 .until

def wait_for(self, func, target=None, timeout=self.timeout):
try:
WebDriverWait(self, timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, func)))
except TimeoutException:
if not target:
raise WebDriverException('Wait for: "%s" failed!' % inspect.getsource(func).strip())
raise NoSuchElementException(target)

关于Python、Selenium - 处理多个等待条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33649926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com