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.
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()
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
#do something
if 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.dismiss
else
alert.accept
end
Hope it helps!
If you want to Accept or Click the popup, regardless of for what it is then
alert.accept
Where
alert
is object of class selenium.webdriver.common.alert.Alert(driver)
and accept
is method of that object
Source
Try The Code below! Working Fine for me!
alert = driver.switch_to.alert
try:
alert.accept() #If you want to Accept the Alert
except:
alert.dismiss() #If You want to Dismiss the Alert.
that depends on the javascript function that handles the form submission if there's no such function try to submit the form using post