Three ways of dealing with Alert in automation(Python+Webdriver)

来源:互联网 发布:如何申请淘宝官方介入 编辑:程序博客网 时间:2024/05/16 01:06

There are 3 ways of dealing with alert in our automation (I don't think there are only 3 ways).

  1. The method of selenium:
    driver = webdriver.Chrome()
    driver.get("http://www.baidu.com")
    driver.execute_script("alert(\"hello\")")
    time.sleep(3)
    alert = driver.switch_to_alert()
    alert.accept()

  2. Overwrite the alert of Javascript:
    driver = webdriver.Chrome()
    driver.get("http://www.baidu.com")
    script = "window.alert = function(msg){ return true;}"
    driver.execute_script(script)
    driver.execute_script("alert(\"hello\")")

    You will find all alert would not be pop up on this page.

  3. Simulate keystrokes:
    You have to install autopy in your python environment, and the install file at https://pypi.python.org/pypi/autopy/.

    driver = webdriver.Chrome()
    driver.get("http://www.baidu.com")
    driver.execute_script("alert(\"hello\")")
    time.sleep(3)
    autopy.key.tap(autopy.key.K_RETURN)

0 0
原创粉丝点击