Selenium定位嵌套同名Div下第二个按钮遇元素不可交互问题求助
解决Selenium定位第二个按钮时的元素不可交互问题
核心问题分析
你之前用的XPATH会匹配到页面中第一个符合条件的按钮,而你需要的是第二个;另外ElementNotInteractableException通常是因为元素未加载完成、不可见,或者被其他元素遮挡导致的。
具体解决方案
1. 精准定位第二个目标按钮
利用页面中两个wrap-ZOLycUbI父级Div的索引,直接定位第二个Div下的目标按钮:
driver.find_element(By.XPATH, "(//div[@class='wrap-ZOLycUbI'])[2]//button[@class='js-save-load-menu-open-button button-reABrhVR apply-common-tooltip accessible-reABrhVR' and @data-name='save-load-menu']").click()
这里(//div[@class='wrap-ZOLycUbI'])[2]明确指定了第二个父容器,确保定位到的是你需要的第二个按钮。
2. 处理元素不可交互的情况
如果还是报错,优先用显式等待确保元素完全加载且可点击:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待10秒,直到第二个按钮可点击 wait = WebDriverWait(driver, 10) target_button = wait.until(EC.element_to_be_clickable( (By.XPATH, "(//div[@class='wrap-ZOLycUbI'])[2]//button[@class='js-save-load-menu-open-button button-reABrhVR apply-common-tooltip accessible-reABrhVR' and @data-name='save-load-menu']") )) target_button.click()
要是按钮被页面元素遮挡,改用JS强制点击:
target_button = driver.find_element(By.XPATH, "(//div[@class='wrap-ZOLycUbI'])[2]//button[@class='js-save-load-menu-open-button button-reABrhVR apply-common-tooltip accessible-reABrhVR' and @data-name='save-load-menu']") driver.execute_script("arguments[0].click();", target_button)
3. 通过按钮集合选择第二个
先获取所有符合条件的按钮,再选取第二个(注意索引从0开始):
buttons = driver.find_elements(By.XPATH, "//button[@class='js-save-load-menu-open-button button-reABrhVR apply-common-tooltip accessible-reABrhVR' and @data-name='save-load-menu']") if len(buttons) >= 2: buttons[1].click()
内容的提问来源于stack exchange,提问作者tospipdev
相关产品推荐
相关产品推荐

