首页 > 解决方案 > 如何使用 Selenium 和 Python 通过“onclick”找到并单击按钮?

问题描述

一个页面中有2个按钮,这2个按钮的区别是"onclick"

<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('security_div0')">OK</button>

<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('wlan1security_div0')">OK</button>

我在想使用xpath

driver.find_element_by_xpath("//form[@id='update-container-id']/div/div/div/div[2]/div/div[2]/table[1]/tbody/tr[1]/td[8]/div[3]/div/div/div/div[3]/button").click()

但它响应如下错误:

selenium.common.exceptions.ElementNotInteractableException: Message: Element <button id="YesBtn" class="btn btn-primary" type="button"> could not be scrolled into view

有谁可以帮我正确点击第二个按钮?非常感谢。

标签: pythonseleniumselenium-webdriverxpathcss-selectors

解决方案


尝试使用 x 路径//button[@onclick="check_security('wlan1security_div0')"]

driver.find_element_by_xpath("//button[@onclick=\"check_security('wlan1security_div0')\"]").click()

使用 Action 类,

button = driver.find_element_by_xpath("//button[@onclick=\"check_security('wlan1security_div0')\"]")
ActionChains(driver).move_to_element(button).click(button).perform()

使用 java 脚本执行器,

driver.execute_script("javascript:check_security('wlan1security_div0')")

推荐阅读