selenium 点击 弹窗中的确认和取消按钮
html
效果
当点击弹窗上的确认按钮后
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>弹窗示例</title> <style> body{ text-align: center; padding-top: 50px; } </style> </head> <body> <h1>点击按钮显示弹窗</h1> <button onclick="showAlert()">点击弹窗</button> <script> function showAlert() { var result = confirm("这是一个带有确认按钮的弹窗示例!") if (result) { alert("您点击了确认按钮!") } else { alert("您点击了取消按钮!") } } </script> </body> </html>
python
# 导包 from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep from selenium.webdriver.common.alert import Alert from selenium.webdriver.chrome.options import Options # 定义类 class GetEle: def __init__(self,driver): self.driver = driver # 点击触发弹窗的按钮 def c_c(self,loc): driver.find_element(By.CSS_SELECTOR, loc).click() print("完成点击触发按钮") # 调用 if __name__ == '__main__': driver = webdriver.Chrome() # 最大化窗口 driver.maximize_window() # url url=r"D:\python-pro\LoginMess\Login\alert3.html" driver.get(url) # 实例化类 web_e=GetEle(driver) # 点击触发弹窗的按钮 loc_c='button[onclick="showAlert()"]' sleep(5) web_e.c_c(loc_c) # 点击弹窗中的确认按钮 alert = Alert(driver) # 点击确认按钮 # alert.accept() # 点击取消按钮 alert.dismiss() sleep(5) driver.quit()