在python、selenium中,如何设置等待的错误消息?
我有以下代码:在python、selenium中,如何设置等待的错误消息?,python,selenium,timeoutexception,Python,Selenium,Timeoutexception,我有以下代码: WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(click)) 现在,这有时会失败,我知道它失败的原因。但这个错误给了我 TimeoutException: Message: 这是没有用的。我可以设置这个消息吗 一个简单的试块就可以了吗 try: WebDriverWait(self.driver, 20).until(expected_conditio
WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(click))
现在,这有时会失败,我知道它失败的原因。但这个错误给了我
TimeoutException: Message:
这是没有用的。我可以设置这个消息吗 一个简单的试块就可以了吗
try:
WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(click))
except TimeoutException:
print("Something")
#or do anything else like self.browser.close()
print (traceback.format_exc())
如果您想编辑消息本身,这将是另一回事,那么您必须在Python中为这种情况创建自定义错误消息,或者创建自定义异常。
希望这是您正在寻找的东西。我编写了一个愚蠢的包装器类。这将始终输出“等待时超时”,而不是空白文本。如果需要更具体的文本,则必须创建一个包装类或一个应用函数“get_error”的新等待类。我在底部包含了jquery动画等待示例
'''
Wrapper for WebDriverWait
'''
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
class Wait(WebDriverWait):
def __init__(self, driver, timeout):
self.driver = driver
self.timeout = timeout
self.wait = WebDriverWait(driver, timeout)
def until(self, condition):
try:
self.wait.until(condition)
except TimeoutException as exception:
error_func = getattr(condition, "get_error", None)
if callable(error_func):
raise TimeoutException(error_func())
else:
raise TimeoutException("Timed out on wait")
def until_not(self, condition):
try:
self.wait.until_not(condition)
except TimeoutException as exception:
error_func = getattr(condition, "get_error", None)
if callable(error_func):
raise TimeoutException(error_func())
else:
raise TimeoutException("Timed out on wait")
WaitForAnimation类:
'''
Wait for a jquery animation to finish
'''
from selenium.webdriver.support import expected_conditions
class WaitForAnimation(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return not driver.execute_script("return jQuery('"+self.locator+"').is(':animated')")
def get_error(self):
return "Timed out waiting for animation of " + self.locator
你不必尝试/除了或包装任何东西
message
只是until()
方法的一个参数
WebDriverWait(self.driver, 20).until(
expected_conditions.element_to_be_clickable(click),
message='My custom message.',
)
这将产生:
selenium.common.exceptions.TimeoutException: Message: My custom message.
我认为他们必须允许某种方式设置错误消息。一直发送一个空字符串似乎很愚蠢。哈哈,这很愚蠢,因为他们根本没有考虑到会发生这种类型的错误。这就是为什么您必须将这个特殊情况添加到异常处理中(我从来没有这样做过),或者创建一个自定义异常(有很多youtube和其他类型的文档用于此)。也许其他人有办法。当你发现谷歌搜索结果是你自己的问题时,那是令人沮丧的时刻。这很有趣。我在文档中看到了这个参数,但它没有说明它的作用。