Python Selenium鼠标悬停点击CourtReserve子菜单失败求助
Selenium自动化CourtReserve预约时悬停菜单点击失败问题
问题描述
作为Selenium新手,尝试自动化CourtReserve的预约流程,无法实现鼠标悬停在“Book a Court”菜单上并点击其子菜单的“Indoor”选项。查阅多篇帖子仍未解决,相关信息如下:
尝试的代码
# Set up the driver, and log in. respMenu= driver.find_element(by=By.ID, value="respMenu") book_a_court = respMenu.find_element(by=By.XPATH,value ="//a[contains(.,'Book a Court')]") indoor = respMenu.find_element(by=By.XPATH,value ="//a[contains(.,'Indoor')]") ActionChains(driver=driver).move_to_element(book_a_court).click(indoor).perform()
页面HTML结构片段
<ul id="respMenu" class="ace-responsive-menu" data-menu-style="horizontal"> <li class="fn-ace-parent-li " data-sm-show=true> <a href="#" data-sm-show=true class="parent-header-link"> <span>Programs</span> </a> <ul> <!-- Programs子菜单内容 --> </ul> </li> <li class="fn-ace-parent-li" data-sm-show=true> <a href="#" data-sm-show=true class="parent-header-link"> <span>Book a Court</span> </a> <ul> <li class="fn-ace-parent-li"> <a href="/Online/Reservations/Bookings/5881?sId=294"> <span>Indoor</span> </a> </li> <li class="fn-ace-parent-li"> <a href="/Online/Reservations/Bookings/5881?sId=295"> <span>Outdoor </span> </a> </li> <li class="fn-ace-parent-li "> <a href="/Online/MyProfile/MyReservations/5881"> <span>My Reservations</span> </a> </li> </ul> </li> </ul>
错误信息
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: https://app.courtreserve.com/Online/Portal/Index/5881#mm-2 has no size and location
解决方案
问题根源
错误提示元素不可交互、无尺寸和位置,核心原因:
- 子菜单“Indoor”默认隐藏,直接查找时仅能获取DOM节点,但元素未渲染为可见状态,无法触发点击
- 悬停操作后未等待子菜单完全显示就执行点击,时序不匹配
修正后的代码
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.webdriver.common.action_chains import ActionChains # 登录后执行以下操作 # 1. 等待主菜单容器加载完成 respMenu = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "respMenu")) ) # 2. 定位"Book a Court"的父li元素(菜单显示逻辑通常绑定在父容器上) book_a_court_li = respMenu.find_element(By.XPATH, ".//li[.//span[text()='Book a Court']]") # 3. 鼠标悬停到父li上,触发子菜单展开 ActionChains(driver).move_to_element(book_a_court_li).perform() # 4. 等待"Indoor"链接可见并可点击 indoor_link = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, ".//span[text()='Indoor']/parent::a")) ) # 5. 点击Indoor选项 indoor_link.click()
关键优化点
- 用
WebDriverWait替代直接查找,确保元素加载完成后再操作,避免页面渲染延迟问题 - 定位父
<li>而非<a>标签,多数下拉菜单的显示事件绑定在父容器上,悬停父元素更稳定 - 悬停后等待子菜单元素可点击,确保元素完全渲染并处于交互状态
- 使用精准XPATH定位:通过
span文本锁定目标<a>标签,避免匹配到相似文本的其他元素
内容的提问来源于stack exchange,提问作者DutchBro
相关产品推荐
相关产品推荐

