Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

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 a popup window( Javascript Alert). I am not sure, how to click the popup through webdriver.

Any idea of how to do it?

Thanks

1 Answer

0 votes
by (62.9k points)

Here is a solution: 

from selenium import webdriver

 

browser = webdriver.Firefox()

browser.get("https://intellipaat.com/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 like this:

 

from selenium import webdriver

 

browser = webdriver.Firefox()

browser.get("https://intellipaat.com/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("https://intellipaat.com/alert.html")

 

try:

    alert = browser.switch_to_alert()

    print alert.text

    alert.accept()

except:

    print "no alert to accept"

browser.close()

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...