弹窗处理通常有三种:Alert类型弹框,Confirm类型弹框,Prompt类型弹框
Alert类型弹框:只有信息及确认按钮
Confirm类型弹框:有信息、确认和取消按钮
Prompt类型弹框:可输入文本内容,有信息、确认和取消按钮
处理JS弹框,目标就是关闭弹出框
selenium中提供了如下方法来处理弹框:
1 # 获取alert对象 2 driver.switch_to.alert 3 # 确定 4 driver.switch_to.alert.accept() 5 # 取消 6 driver.switch_to.alert.dismiss() 7 # 打印弹窗信息 8 driver.switch_to.alert.text 9 # 弹窗中输入内容 10 alert.send_keys()
代码如下:
1 import time 2 from selenium.webdriver.common.alert import Alert 3 from selenium import webdriver 4 from selenium.webdriver.common.by import By 5 from selenium.webdriver.support.wait import WebDriverWait 6 7 driver = webdriver.Chrome() 8 driver.get("https://www.baidu.com") 9 driver.maximize_window() 10 11 wait = WebDriverWait(driver, 10) 12 13 driver.find_element(By.XPATH, '//span[text()="设置"]').click() 14 driver.find_element(By.XPATH, '//span[text()="搜索设置"]').click() 15 16 time.sleep(5) 17 driver.find_element(By.XPATH, '//a[text()="保存设置"]').click() 18 19 # 获取alert对象 20 # alert = driver.switch_to.alert 21 alert = Alert(driver) 22 23 # 打印弹窗信息 24 text = alert.text 25 print(text) 26 27 # 确定 28 alert.accept() 29 30 time.sleep(3) 31 driver.quit()
标签:处理,text,driver,弹框,import,alert,弹窗 From: https://www.cnblogs.com/liyongmei/p/17005248.html