標籤:顯示 步驟 需要 cond expect expected from find lse
前言
系統彈窗這個是很常見的情境,有時候它不彈出來去操作的話,會拋異常。那麼又不知道它啥時候會出來,那麼久需要去判斷彈窗是否彈出了。
本篇接著Selenium2+python自動化42-判斷元素(expected_conditions)講expected_conditions這個模組
一、判斷alert源碼分析
class alert_is_present(object):
""" Expect an alert to be present."""
"""判斷當前頁面的alert彈窗"""
def __init__(self):
pass
def __call__(self, driver):
try:
alert = driver.switch_to.alert
alert.text
return alert
except NoAlertPresentException:
return False
1.這個類比較簡單,初始化裡面無內容
2.__call__裡面就是判斷如果正常擷取到彈出窗的text內容就返回alert這個對象(注意這裡不是返回Ture),沒有擷取到就返回False
二、執行個體操作
1.前面的操作步驟最佳化了下,為了提高指令碼的穩定性,確保元素出現後操作,
這裡結合WebDriverWait裡的方法:Selenium2+python自動化38-顯式等待(WebDriverWait)
2.實現步驟如下,這裡判斷的結果返回有兩種:沒找到就返回False;找到就返回alert對象
3.先判斷alert是否彈出,如果彈出就點確定按鈕accept()
三、參考代碼
# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
url = "https://www.baidu.com"
driver.get(url)
mouse = WebDriverWait(driver, 10).until(lambda x: x.find_element("link text", "設定"))
ActionChains(driver).move_to_element(mouse).perform()
WebDriverWait(driver, 10).until(lambda x: x.find_element("link text", "搜尋設定")).click()
# 選擇設定項
s = WebDriverWait(driver, 10).until(lambda x: x.find_element("id", "nr"))
Select(s).select_by_visible_text("每頁顯示50條")
# 點儲存按鈕
js = ‘document.getElementsByClassName("prefpanelgo")[0].click();‘
driver.execute_script(js)
# 判斷彈窗結果 交流QQ群: 232607095
result = EC.alert_is_present()(driver)
if result:
print result.text
result.accept()
else:
print "alert 未彈出!"
Selenium2+python自動化47-判斷彈出框存在(alert_is_present)