下面是一个示例,演示如何编写一个通用方法,同时支持显示等待和隐式等待:
pythonCopy
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
def wait_and_click(driver, by, value, wait_type='implicit', timeout=10):
"""
等待元素可点击并点击它。
Args:
driver: WebDriver 对象。
by: 元素定位方法,如 By.ID、By.XPATH 等。
value: 元素定位表达式。
wait_type: 等待类型,可以是 'implicit'(隐式等待)或 'explicit'(显示等待),默认为 'implicit'。
timeout: 等待超时时间,单位为秒,默认为 10。
Returns:
如果成功点击元素,返回 True;如果超时或找不到元素,返回 False。
"""
try:
if wait_type == 'implicit':
driver.implicitly_wait(timeout)
element = driver.find_element(by, value)
element.click()
return True
elif wait_type == 'explicit':
wait = WebDriverWait(driver, timeout)
element = wait.until(EC.element_to_be_clickable((by, value)))
element.click()
return True
else:
raise ValueError(f"Unsupported wait_type: {wait_type}")
except TimeoutException:
return False
except Exception as e:
print(f"Failed to wait and click element: {e}")
return False
在这个示例中,我们定义了一个名为 wait_and_click 的函数,它接受四个参数:
driver:WebDriver 对象。by:元素定位方法,如 By.ID、By.XPATH 等。value:元素定位表达式。wait_type:等待类型,可以是 ‘implicit’(隐式等待)或 ‘explicit’(显示等待),默认为 ‘implicit’。timeout:等待超时时间,单位为秒,默认为 10。
该函数首先检查 wait_type 参数,如果是 ‘implicit’,则设置隐式等待时间为 timeout,然后查找指定的元素并点击它。如果是 ‘explicit’,则创建一个显示等待对象并等待元素可点击,然后点击它。如果 wait_type 参数不是 ‘implicit’ 或 ‘explicit’,则抛出 ValueError 异常。
如果成功点击元素,函数返回 True;如果超时或找不到元素,函数返回 False。
示例用法:
pythonCopy
driver = webdriver.Chrome()
# 使用隐式等待等待并点击元素
result = wait_and_click(driver, By.ID, 'my_button_id', wait_type='implicit', timeout=10)
print(f"隐式等待结果:{result}")
# 使用显示等待等待并点击元素
result = wait_and_click(driver, By.ID, 'my_button_id', wait_type='explicit', timeout=10)
print(f"显示等待结果:{result}")
driver.quit()
在这个示例中,我们创建了一个 WebDriver 对象 driver,然后分别使用隐式等待和显示等待等待并点击 ID 为 my_button_id 的元素,并输出结果。