在html的javascript交互中主要有Alert警告框、Confirm確認(rèn)框、Prompt消息對(duì)話框。
部分小伙伴學(xué)了selenium的alert后,就不管啥彈出框都去用alert,這是行不通的,看到彈出框,先要確定是不是alert,是才能用,不是的話肯定不能用。
有些彈出框是div層,這種跟平常定位方法一樣
有些彈出框是嵌套的iframe層,這種切換iframe就可以了
有些彈出框比較坑,是嵌入的一個(gè)窗口
text:獲取文本值
accept() :點(diǎn)擊"確認(rèn)"
dismiss() :點(diǎn)擊"取消"或者叉掉對(duì)話框
send_keys() :輸入文本值 --僅限于prompt,在alert和confirm上沒(méi)有輸入框
4.代碼
#!/usr/bin/env python#
#encoding:utf-8
import time
import selenium
from seleniumimport webdriver
from selenium.webdriver.common.action_chainsimport ActionChains
import sys
reload(sys)
sys.setdefaultencoding("utf-8" )
#打開(kāi)網(wǎng)頁(yè)
web=webdriver.Chrome()
url='E:\新建文本文檔.html'
web.get(url)
web.maximize_window()
#設(shè)置只能等待時(shí)間
web.implicitly_wait(30)
#Alert警告框、Confirm確認(rèn)框、Prompt消息對(duì)話框。
#alert
web.find_element_by_id('alert').click()
time.sleep(3)
alert1=web.switch_to_alert()
print(alert1.text)#顯示彈出框內(nèi)容
alert1.accept()#彈出框確認(rèn)
#comfirm
web.find_element_by_id('confirm').click()
time.sleep(3)
web.switch_to_alert().accept()#確認(rèn)按鈕
time.sleep(3)
web.find_element_by_id('confirm').click()
time.sleep(3)
web.switch_to_alert().dismiss()#取消按鈕
#prompt
web.find_element_by_id('prompt').click()
web.switch_to_alert().send_keys('selenium')
time.sleep(3)
web.switch_to_alert().accept()
time.sleep(3)
web.refresh()
time.sleep(3)
web.find_element_by_id('prompt').click()
time.sleep(3)
web.switch_to_alert().send_keys('selenium')
time.sleep(3)
web.switch_to_alert().dismiss()
#退出瀏覽器
time.sleep(3)
web.quit()
