There are 3 ways of dealing with alert in our automation (I don't think there are only 3 ways).
- 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()
- 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.
- 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)