Making an alert box in the browser using selenium python

I want to create an alert box in the browser.

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

      

To create an alert box I am 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, a warning window is displayed. But I have, in all cases there are exceptions: selenium.common.exceptions.WebDriverException: Message: Failed to find value field

.

What is the correct way to create an alert box?

+3


source to share


1 answer


This seems to be the problem geckodriver

. Despite the thrown exception "Failed to find value field"

, you can still handle the open warning, so you can apply the 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 mentioned in the comments, you can use Chrome

, IE

etc.

+2


source







All Articles