[Python] How to handle alerts in selenium?

Posted in :

在python 裡處理 alert 滿簡單的,範例如下:

from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException

if __name__ == '__main__':
    driver = webdriver.Firefox()
    driver.set_window_size(1400, 1000)
    driver.get('http://localhost:8001/page2.html')

    try:
        driver.switch_to.alert.accept()
        print('Alarm! ALARM!')
    except NoAlertPresentException:
        print('*crickets*')

比較特別的地方是,當 alert popup 時,會造成無法 access driver.current_url

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *