如何重构Python Selenium代码的try/except块以规避DRY原则违反?
重构方案
1. 修正close_popup函数的异常捕获逻辑
原函数的except块写法存在语法错误,同时将driver作为参数传入,避免依赖全局变量,更符合Python模块化风格:
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def close_popup(driver): try: # 改用element_to_be_clickable确保元素可交互,而非仅存在于DOM popup_btn = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//x-button'))) popup_btn.click() # 用显式等待替代time.sleep,等待弹窗消失 WebDriverWait(driver, 5).until(EC.invisibility_of_element_located((By.XPATH, '//x-button'))) print("弹窗已关闭") except NoSuchElementException: print("未检测到弹窗")
2. 封装通用安全点击函数
将重复的元素定位、点击逻辑封装成可复用函数,自动处理弹窗拦截异常:
def safe_click_element(driver, locator, wait_timeout=10): """ 安全点击元素,遇弹窗拦截时自动关闭弹窗并重试 :param driver: WebDriver实例 :param locator: 元素定位器,格式为(By.XXX, "定位值") :param wait_timeout: 元素等待超时时间 """ try: target_element = WebDriverWait(driver, wait_timeout).until(EC.element_to_be_clickable(locator)) target_element.click() except ElementClickInterceptedException: print("点击被弹窗拦截,尝试关闭弹窗...") close_popup(driver) # 重试点击操作 target_element = WebDriverWait(driver, wait_timeout).until(EC.element_to_be_clickable(locator)) target_element.click()
3. 简化主逻辑调用
现在主代码只需一行即可完成目标元素点击,完全符合DRY原则:
# 定义目标元素定位器 target_locator = (By.LINK_TEXT, "Click here!") # 执行安全点击 safe_click_element(driver, target_locator)
额外优化建议
- 可给
safe_click_element添加重试次数参数,应对弹窗关闭后仍无法点击的极端情况 - 统一管理所有元素定位器,将其集中定义为常量,进一步提升代码可维护性
内容的提问来源于stack exchange,提问作者dbaser
相关产品推荐
相关产品推荐

