Selenium Python井字棋自动化测试:checkForWinner方法未调用问题
问题分析与解决方案
1. 先解决「checkForWinner()未被调用」的核心问题
- 必须在每次点击棋盘格子后主动调用该方法,比如在
test_playGame方法里,每执行一次点击操作就添加self.checkForWinner(load_browser)调用。如果没有这个触发逻辑,方法自然不会执行。
2. 修复checkForWinner方法的逻辑缺陷
当前代码存在几个关键问题,直接导致功能失效:
- 错误的元素判断方式:直接用
Tags.resultOh这类变量判断无效,Selenium需要通过元素定位(如find_element)来检查获胜文本是否显示。修改后的代码示例:from selenium.common.exceptions import NoSuchElementException def checkForWinner(self, load_browser): # 检查O获胜的元素是否可见 try: load_browser.find_element(By.ID, Tags.resultOh).is_displayed() winner = 'O' LOGGER.debug('Winner O') assert winner == 'O', "获胜者应为O" return winner # 返回结果终止游戏流程 except NoSuchElementException: pass # 检查X获胜的元素是否可见 try: load_browser.find_element(By.ID, Tags.resultEx).is_displayed() winner = 'X' LOGGER.debug('Winner X') assert winner == 'X', "获胜者应为X" return winner except NoSuchElementException: pass # 检查平局的元素是否可见 try: load_browser.find_element(By.ID, Tags.resultTie).is_displayed() winner = 'None' LOGGER.debug('Tie') assert winner == 'None', "应为平局" return winner except NoSuchElementException: # 游戏未结束,返回None继续流程 return None - 递归调用导致无限挂起:原代码
else分支直接递归调用test_playGame,会引发无限循环或等待,最终导致脚本挂起。应改为在主逻辑中循环执行点击+检查,根据checkForWinner的返回结果决定是否终止游戏。
3. 解决脚本挂起、浏览器无法关闭的问题
- 添加显式等待:检查获胜元素时设置超时时间,避免无限等待:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException def checkForWinner(self, load_browser): wait = WebDriverWait(load_browser, 10) # 设置10秒超时 try: wait.until(EC.visibility_of_element_located((By.ID, Tags.resultOh))) winner = 'O' LOGGER.debug('Winner O') assert winner == 'O' return winner except TimeoutException: pass # 同理处理X获胜和平局的检查逻辑 - 强制资源清理:用
try-finally块确保浏览器无论是否出错都能关闭:def test_main(self): load_browser = webdriver.Chrome() try: load_browser.get("你的井字棋游戏URL") while True: self.test_playGame(load_browser) # 执行一次格子点击 winner = self.checkForWinner(load_browser) if winner is not None: break # 游戏结束,退出循环 finally: load_browser.quit() # 确保浏览器强制关闭
4. 验证调用逻辑
确认test_playGame方法中每次点击后都触发了检查,示例:
def test_playGame(self, load_browser): # 定位一个未被占用的格子并点击 empty_cell = load_browser.find_element(By.CSS_SELECTOR, ".cell:not(.occupied)") empty_cell.click() # 点击后立即检查获胜状态 self.checkForWinner(load_browser)
内容的提问来源于stack exchange,提问作者CodenameCaptainFuture
相关产品推荐
相关产品推荐

