5

This question deals with setting the UnexpectedAlertBehaviour of a Selenium webdriver in Java. How do you do the same thing in Python's ChromeDriver?

I have tried the following;

    options = ChromeOptions()
    options.headless = True
    options.set_capability("UNEXPECTED_ALERT_BEHAVIOUR", "ACCEPT")
    options.set_capability("unexpectedAlertBehaviour", "accept")
    options.set_capability("CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR", "ACCEPT")
    options.set_capability("UnexpectedAlertBehaviour", "ACCEPT")
    webdriver.DesiredCapabilities.CHROME["unexpectedAlertBehaviour"] = "accept"
    cls.driver = webdriver.Chrome(chrome_options=options)

However, I am still randomly experiencing this unexpectedalertpresent exception:

selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: Message: unexpected alert open: {Alert text : }

When I run the browser in non headless mode (head mode?) I see no such alerts, but the test still randomly fails with this exception, despite my efforts to set this elusive option.

n00b
  • 4,341
  • 5
  • 31
  • 57
  • Have you tried catching the error as stated in the python coded answer to your linked question here: https://stackoverflow.com/a/30731973/7592395 – skymon Aug 28 '19 at 21:48
  • Id rather that unexpected alerts alwasy be accepted rather then handling an exception, because I want the test to continue, even if there is an unexpected alert. I can switch to the alert if i know it exist, but in this case the alert appearing is random (sometimes it pops sometimes it doesnt). my next step is to always try accepting an alert and swalling the exception if the alert doesnt exist, but it seems kind of ugly. – n00b Aug 28 '19 at 21:51

1 Answers1

8

As chromedriver becoming W3C compliant . We need use unhandledPromptBehavior Checked on ChromeDriver 76.0.3809.126 (Runs in W3C standard compliant mode by default)

chrome_options = Options()
chrome_options.set_capability('unhandledPromptBehavior', 'accept')
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com")
driver.execute_script('alert(\"HI\");')
time.sleep(10)
print(driver.title)
time.sleep(10)

Reference Chromedriver: Issue 2597: Support new unhandledPromptBehavior modes

Rahul L
  • 4,249
  • 15
  • 18
  • 1
    That worked thanks. FYI to future googlers you can use the same code for the Firefox geckodriver (specifically the set_capability line) and it works the same. Also for the "accept and notify" option, i found it only worked if i set it as a single word "acceptandnotify" however it will still cause unit tests to fail with that option. – n00b Aug 29 '19 at 13:43