0

Why switching to alert through selenium is not stable?

For example.
1. Run a code and all good. Everything worked out well. But if this code is run in a few minutes, then there may be errors. There is no element you can click on, for example. And so on.
2. On one site there is an alert window.

alert = driver.switch_to_alert()
alert.dismiss()

So I close it. But he works through time. All is well, then errors.

for al in range(3):
    try:
        alert = driver.switch_to_alert()
        alert.dismiss()
        time.sleep(randint(1, 3))
    except:
        pass

I wrote and everything works out as it should.
But I think that this is not beautiful.
Why is everything so unstable?
Thank you very much.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Serhii
  • 1,367
  • 3
  • 13
  • 31
  • Are there multiple alerts? Multiple tabs? What exactly stops working if you just dismiss the alert once? Perhaps you need to explicitly switch back to the main window/tab. – Chuk Ultima Feb 17 '18 at 08:23
  • 2
    Please provide an example of complete code which sometimes works and sometimes doesn't, i.e., [mcve](https://stackoverflow.com/help/mcve). Your second part is a bit confusing. *Everything works but it's not beautiful* implies a different question. – Reti43 Feb 17 '18 at 08:32
  • Selenium should only be used for testing not scraping. –  Feb 17 '18 at 09:21

2 Answers2

3

As per your code block there are a couple of issues which you need to address as follows :

  • Switching to an Alert : The method switch_to_alert() is Deprecated and you should be using switch_to.alert instead. The API Docs clearly mentions the following :

     def switch_to_alert(self):
         """ Deprecated use driver.switch_to.alert
         """
         warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)
         return self._switch_to.alert
    
  • Wait for the Alert to be present : You should always induce WebDriverWait for the Alert to be present before invoking accept() or dismiss() as follows :

    WebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

This will click the OK button on the alert:

driver.switch_to.alert.accept() 

This will click the CANCEL button on the alert:

driver.switch_to.alert.dismiss()     
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77