Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any alert exists using selenium with python

I'm trying to write a test with selenium in python language for a web page that manages users. In this page someone can add role for users and if a role exists while adding it, an alert raises. I don't know if the alert is a javascript alert or an element of the web page. I want to automatically check the existence of the alert, because checking for the role in the list wastes time and has an enormous load. I tried this:

browser = webdriver.Firefox() browser.get("url") browser.find_the_element_by_id("add_button").click() try:     alert = browser.switch_to_alert()     alert.accept()     print "alert accepted" except:     print "no alert" 

But it didn't work and I got the "UnexpectedAlertPresentException". I also tried this:

browser = webdriver.Firefox() browser.get("url") browser.find_the_element_by_id("add_button").click() s = set(browser.window_handles) s.remove(browser.current_window_handle) browser.switch_to_window(s.pop())  

But I got the same exception. Additionally, I tried to access the alert with firebug to check if I can get access with its properties, but right click was disabled. I need a solution very quickly, even in other languages. I can understand the approach anyway. I will appreciate any help.

like image 329
Zeinab Abbasimazar Avatar asked Sep 25 '13 10:09

Zeinab Abbasimazar


People also ask

How do you check if there is any alert exists in Selenium?

We can check if an alert exists with Selenium webdriver. An alert is created with the help of Javascript. We shall use the explicit wait concept in synchronization to verify the presence of an alert. Let us consider the below alert and check its presence on the page.

How do I get alert text in Selenium?

Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the method switchTo(). alert(). getText(). Finally we shall use the accept method to accept the alert and dismiss method to dismiss it.


1 Answers

What I do is to set a conditional delay with WebDriverWait just before the point I expect to see the alert, then switch to it, like this:

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException  browser = webdriver.Firefox() browser.get("url") browser.find_element_by_id("add_button").click()  try:     WebDriverWait(browser, 3).until(EC.alert_is_present(),                                    'Timed out waiting for PA creation ' +                                    'confirmation popup to appear.')      alert = browser.switch_to.alert     alert.accept()     print("alert accepted") except TimeoutException:     print("no alert") 

WebDriverWait(browser,3) will wait for at least 3 seconds for a supported alert to appear.

like image 104
A.R. Avatar answered Oct 04 '22 11:10

A.R.