十七.python+selenium之alert(警告)弹框处理。

alert弹窗处理一般有两种:

第一种,点确认使用   .accept()  函数

第二种,点取消或是点右上角的x,使用   .dismiss()  函数

延用上一篇的代码,在百度设置点保存设置后,会弹出一个框,然后对弹框进行点击确认 或是 点击x的操作。

以下是演示代码:

#coding:utf-8
from selenium import webdriver
from selenium.webdriver.support.select import Select #导入Select包
from selenium.webdriver.common.action_chains import ActionChains #导入鼠标事件包
from time import sleep
bro = webdriver.Chrome()
bro.maximize_window()
bro.get("https:www.baidu.com")
bro.implicitly_wait(10)
a = bro.find_element_by_link_text("设置")
ActionChains(bro).move_to_element(a).perform() #通过鼠标移动到设置上进行操作
bro.find_element_by_link_text("搜索设置").click()
sleep(3) #在使用谷歌浏览器时发现加入了休眠时间下面运行时才能找到元素
#格式 Select(对应元素).select_by_对应方法("方法的对应值")
s = bro.find_element_by_id("nr")
#Select(s).select_by_index("1") #通过索引定位(从0开始计数)
# Select(s).select_by_visible_text("每页显示20条") #通过文本值定位
Select(s).select_by_value("20") #通过value值定位
sleep(1)
bro.find_element_by_link_text("保存设置").click()
sleep(2)
a = bro.switch_to_alert() #切换到alert弹框上
print a.text #打印弹框的文本内容
#a.accept() #accept()表示点击确认按钮
a.dismiss() #表示点击一下x按钮
sleep(2)
bro.quit()

猜你喜欢

转载自blog.csdn.net/Static_at/article/details/81463426
今日推荐