Selenium 处理chrome弹窗
Selenium 处理chrome弹窗
参考:https://blog.csdn.net/qq_39314932/article/details/123279659
HTML弹窗:
1、在实际系统中,在完成某些操作时会弹出对话框来提示,主要分为
- "警告消息框",alert,
- "确认消息框",confirm,
- "提示消息对话",prompt。
Selenium处理方法:
1、Selenium中的WebDriver对象提供了switch_to_alert()方法定位(捕获)到各种弹窗(alert、confirm、prompt)
2、WebDriver对象在处理弹框时主要有以下几种方法:
⑴ switch_to_alert():定位弹出的对话框
⑵ text:获取对话框文本值
⑶ accept():相当于点击"确认"
⑷ dismiss():相当于点击"取消"
⑸ send_keys():输入值,该方法只能在prompt类弹框中使用
例如:
driver.find_element_by_xpath('//*[@id="se-setting-7"]/a[2]').click()
# 此时就会弹出alter类对话框,使用switch_to_alert()定位到弹窗
alter = driver.switch_to_alert()
print(alter)
print(driver.switch_to.alert)
# 打印对话框内容
print(alter.text)
# 点击对话框[确定]按钮以关闭对话框
alter.accept()
time.sleep(2)
#关闭对话框后继续操作页面
driver.find_element_by_id("kw").send_keys("不怕猫的耗子A")
注:
1、在编辑器中写switch_to_alert()方法时会出现横线(删除线),这个表示该方法太老了,后面可能会放弃使用
⑴因此我们还可以使用switch_to.alert方法
2、两个方法稍微有点差距
⑴switch_to_alert():是类方法
⑵switch_to.alert:是类属性
⑶但是两者的返回值都是一样的:都是一个alter对象
3、弹框肯定是在当前Selenium指向的窗口中的(在同一页面中),因此在关闭弹出框后,可继续操作本页面的元素
其他方法
1、定位弹出框不仅可以使用上面的"switch_to.alert"和"switch_to_alert()"方法
2、还可以通过其他方法进行跳转到alert
⑴这里需要用到Alert模块,首先进行导入from selenium.webdriver.common.alert import Alert
alter = Alert(driver)
# 打印对话框内容
print(alter.text)
# 点击对话框[确定]按钮以关闭对话框
alter.accept()
对话框处理
参考:https://www.likecs.com/show-203523725.html
https://www.codenong.com/cs106208710/
https://www.likecs.com/show-204426683.html
显示通知:
这东西不属于页面alert弹框,而是属于浏览器的设置项。
要关掉它,需要对浏览器进行属于配置。具体见下面脚本:
from selenium import webdriver
import time
options = webdriver.ChromeOptions()
prefs = {
'profile.default_content_setting_values':{
'notifications':2
}
}
options.add_experimental_option('prefs',prefs)
driver = webdriver.Chrome(options = options)
driver.get("https://weibo.com/")
driver.implicitly_wait(10)
剪贴板通知:
同样可设置chrome偏好权限,但注意该权限在chrome隐身模式下无效:
ChromeOptions options = new ChromeOptions();
// 1 表示允许粘贴剪贴板中内容
options.addUserProfilePreference("profile.default_content_setting_values_clipboard",1);
IWebdriver driver = new Iwebdriver(options);
相当于更改这里的内容:
存储权限通知:
options=webdriver.ChromeOptions()
options.add_argument('--unlimited-storage')
driver=webdriver.Chrome(chrome_options = options)
Chrome的权限参考网址:
https://developer.chrome.com/apps/declare_permissions