Search code examples
pythonseleniumselenium-webdriverwebdriver

During handling UnexpectedAlertPresentException, NoAlertPresentException occurs in python selenium


I was handling UnexpectedAlertPresentException which often occurs, So I made try-except codes to deal with it. I was about to return the content of Unexpected Alert, So My code is

wait = WebDriverWait(driver2, 10)
try:
    element = wait.until(EC.element_to_be_clickable((By.NAME, 'wlike_limit')))
except UnexpectedAlertPresentException:
    print("UnexpectedAlertPresentException, ",driver2.switch_to.alert.text)

But it also gives me "NoAlertPresentException" while trying to print the text of the unexpected alert.

UnexpectedAlertPresentException           Traceback (most recent call last)
<ipython-input-52-543c0fff5a64> in <module>
     16 try:
---> 17    element = wait.until(EC.element_to_be_clickable((By.NAME, 'wlike_limit')))
     18 except UnexpectedAlertPresentException:

UnexpectedAlertPresentException: Alert Text: 
Message: unexpected alert open: {Alert text: }
  (Session info: chrome=84.0.4147.125)


During handling of the above exception, another exception occurred:

NoAlertPresentException                   Traceback (most recent call last)
<ipython-input-52-543c0fff5a64> in <module>
     17    element = wait.until(EC.element_to_be_clickable((By.NAME, 'wlike_limit')))
     18 except UnexpectedAlertPresentException:
---> 19    print("UnexpectedAlertPresentException, ",driver2.switch_to.alert.text)
     20 

Could anyone help me deal with this problem?


Solution

  • This error message...

    NoAlertPresentException                   Traceback (most recent call last)
    

    ...implies that though you attempted to handle an Alert but there was no such alert.


    Analysis

    This line of code:

    except UnexpectedAlertPresentException:
            print("UnexpectedAlertPresentException, ",driver2.switch_to.alert.text)
            
    

    would switch to the alert and retrieve the text when your code block faces UnexpectedAlertPresentException. However it seems there was no alert present.

    Now in in the try{} block:

    element = wait.until(EC.element_to_be_clickable((By.NAME, 'wlike_limit')))
    

    This line won't raise any alert as you are not interacting with the element. Hence, the catching UnexpectedAlertPresentException doesn't looks useful to me.


    Conclusion

    The try-catch{} block for handling UnexpectedAlertPresentException doesn't looks useful to me. Perhaps your previous code block can provide some hint in which circumstances you wanted to handle UnexpectedAlertPresentException.


    References

    You can find a couple of relevant discussions in: