Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click the javascript popup through webdriver

Tags:

I am scraping a webpage using Selenium webdriver in Python

The webpage I am working on, has a form. I am able to fill the form and then I click on the Submit button.

It generates an popup window( Javascript Alert). I am not sure, how to click the popup through webdriver.

Any idea how to do it ?

Thanks

like image 924
Kiran Avatar asked Dec 25 '11 20:12

Kiran


People also ask

Can Webdriver handle JavaScript popup?

WebDriver can get the text from the popup and accept or dismiss these alerts.

Can I use JavaScript with Selenium Webdriver?

Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want. A webdriver must be installed for selenium to work. All it takes to execute Javascript is calling the method execute_script(js) where js is your javascript code.

What is alert () in driver switchTo ()?

An alert can be of three types – a prompt which allows the user to input text, a normal alert and a confirmation alert. By default, the webdriver can only access the main page, once an alert comes up, the method switchTo(). alert() is used to shift the focus webdriver control to the alert.


1 Answers

Python Webdriver Script:

from selenium import webdriver

browser = 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 webdriver

browser = 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 webdriver

browser = 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()
like image 143
Mike Grace Avatar answered Sep 20 '22 16:09

Mike Grace