使用Selenium python自动关闭对话框

时间:2014-01-19 09:27:00

标签: python selenium selenium-webdriver

使用Selenium的程序

from selenium import webdriver
browser = webdriver.Firefox()
url = 'any_url'
browser.get(url)
browser.find_element_by_id('empty_cart_btn').click()

创建以下对话框:

enter image description here

Selenium中的代码是自动按OK?

1 个答案:

答案 0 :(得分:3)

selenium.webdriver.common.alert

尝试accept()

以下未经测试的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
url = 'any_url'
browser.get(url)
browser.find_element_by_id('empty_cart_btn').click()

try:
    WebDriverWait(browser, 5).until(EC.alert_is_present(), 'Waiting for alert timed out')

    alert = browser.switch_to_alert()
    alert.accept()
    print "alert accepted"

except TimeoutException:
    print "no alert"