1

I am trying to use selenium to navigate from some page to another:

driver = webdriver.Chrome()
driver.get("...some page...")
...  # the alert does not exist yet and thus cannot be accepted
driver.get("...some other page...") # the alert pops up here and blocks navigation to 'some other page'
# execution never reaches here
...

Now, navigating away from 'some page' triggers an alert, asking to confirm that one really wants to leave the page. This blocks execution forever. An implicit timeout was set, but is not triggered by this. I cannot get selenium to accept the alert, because only appears after calling 'get'.

Is there any way around this?

Thank you very much!

2 Answers2

2

Try following code and let me know if it's not working

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

driver = webdriver.Chrome()
driver.get("...some page...")
try:
    WebDriverWait(driver, 5).until(EC.alert_is_present())
    driver.switch_to_alert().accept()
except TimeoutException:
    print("Alert not found. Move on...)
driver.get("...some other page...")
Andersson
  • 51,635
  • 17
  • 77
  • 129
  • Thanks for the help! This does not solve it though, because the alert does not pop up until `driver.get("...some other page...")`. – Alexander Schlegel Oct 26 '16 at 12:00
  • so use `try/except` block not after `driver.get("...some page...")`, but after `driver.get("...some other page...")` – Andersson Oct 26 '16 at 12:02
  • this won't work either, because execution just stops at `driver.get("...some other page")` (it seems to be blocked by the alert) and therefore would not reach the `try/except` block – Alexander Schlegel Oct 26 '16 at 12:05
  • Have you tried it or it's just your suggestion? Script execution cannot be blocked by alert! – Andersson Oct 26 '16 at 12:10
  • 1
    You're right. Turns out that the problem was somewhere else and I jumped to conclusions. Sorry for the confusion and thanks again for your help! In the end it lead me to the core of the problem. – Alexander Schlegel Oct 26 '16 at 13:05
0

Try overwriting the javascript alert function.

driver.get('https://stackoverflow.com/questions/40259660/how-to-accept-alert-that-is-triggered-by-get-in-selenium-python-chromedriver#40259660')
wmd_input = ref_settings.driver.find_element(By.ID, 'wmd-input')
wmd_input.click()
wmd_input.send_keys('That's a test for a model JS dialog')

#the following line overwrites the alert function
driver.execute_script("""window.alert = function() {};alert = function() {};""")
time.sleep(3)
ref_settings.driver.get('http://stackoverflow.com')
Community
  • 1
  • 1
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99