Alexey Egorov
Alexey Egorov

Reputation: 2410

Creating alert window in browser with python selenium

I want create alert window in browser.

browser = webdriver.Firefox(
    executable_path=geckodriver_path,
    log_path=geckodriver_log_path
)
browser.get(url)

To create alert window I doing:

browser.execute_script("alert('qwer');")

or

browser.execute_script("return alert('qwer');")

or

browser.execute_script("return (function(){alert('qwer'); return 0;})();")

In all cases alert window was displayed. But in all cases I have an Exception: selenium.common.exceptions.WebDriverException: Message: Failed to find value field.

What is right way to create alert window?

Upvotes: 4

Views: 4379

Answers (1)

Andersson
Andersson

Reputation: 52665

This seem to be geckodriver issue. Despite of generated "Failed to find value field" exception you still can handle opened alert, so you might apply below workaround:

from selenium.common.exceptions import WebDriverException

try:
    browser.execute_script("alert('qwer');")
except WebDriverException:
    pass
browser.switch_to.alert.text # output is "qwer"
browser.switch_to.alert.accept() # alert closed

...or, as was mentioned in comments, you can use Chrome, IE, etc

Upvotes: 4

Related Questions