Selenium2+python自動化47-判斷彈出框存在(alert_is_present)

來源:互聯網
上載者:User

標籤:顯示   步驟   需要   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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.