Click the javascript popup through webdriver Click the javascript popup through webdriver selenium selenium

Click the javascript popup through webdriver


Python Webdriver Script:

from selenium import webdriverbrowser = webdriver.Firefox()browser.get("http://sandbox.dev/alert.html")alert = browser.switch_to_alert()alert.accept()browser.close()

Webpage (alert.html):

<html><body>    <script>alert("hey");</script></body></html>

Running the webdriver script will open the HTML page that shows an alert. Webdriver immediately switches to the alert and accepts it. Webdriver then closes the browser and ends.

If you are not sure there will be an alert then you need to catch the error with something like this.

from selenium import webdriverbrowser = webdriver.Firefox()browser.get("http://sandbox.dev/no-alert.html")try:    alert = browser.switch_to_alert()    alert.accept()except:    print "no alert to accept"browser.close()

If you need to check the text of the alert, you can get the text of the alert by accessing the text attribute of the alert object:

from selenium import webdriverbrowser = webdriver.Firefox()browser.get("http://sandbox.dev/alert.html")try:    alert = browser.switch_to_alert()    print alert.text    alert.accept()except:    print "no alert to accept"browser.close()


from selenium import webdriverfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox()#do somethingif EC.alert_is_present:    print "Alert Exists"    driver.switch_to_alert().accept()    print "Alert accepted"else:    print "No alert exists"

More about excepted_conditions https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html


I am using Ruby bindings but here what I found in Selenium Python Bindings 2 documentation:http://readthedocs.org/docs/selenium-python/en/latest/index.html

Selenium WebDriver has built-in support for handling popup dialog boxes. After you’ve triggerd and action that would open a popup, you can access the alert with the following:

alert = driver.switch_to_alert()

Now I guess you can do something like that:

if alert.text == 'A value you are looking for'  alert.dismisselse  alert.acceptend

Hope it helps!