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
WebDriver can get the text from the popup and accept or dismiss these alerts.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With