Alerts take the focus away from the current window and force the browser to read the message.
Alert prevents the user from accessing other parts of the web page until the box is closed.
Alert Types :
When an alert is present on the webpage, we cannot proceed further without handling the popup, and if we try to perform any operation, it throws
We can handle alerts using the
switch_to_alert() method present in selenium python; with the help of this
Syntax to handle Alert
ale = driver.switch_to_alert();
With this alerts API, we can perform the below operations on the pop-up.
1. Accept the popUp by clicking the OK button
2. Dismiss the popUp by clicking the 'X' icon.
3. Get popUp text by getText method
4. Send a text to popUp by send_keys (Applicable for Prompt only)
When do alerts occur on a page: It can occur on a page at any time, but most of it happens on the below timing of the webpage
alert() method displays an alert box with a message and an OK button, an alert box is often used to inform a user about a particular operation like details saved in Database, right-click disabled, Loaded successfully such kind of messages.
Alert is formed using
driver.switchTo().alert();, and store the object
def test_open_alerts(self): driver = webdriver.Chrome(executable_path=r'D:PATHchromedriver.exe') driver.get("https://chercher.tech/java/practice-pop-ups-selenium-webdriver"); driver.find_element_by_name("alert").click(); ale = driver.switch_to_alert() # clicks 'OK' button ale.accept();
ale = driver.switch_to_alert(); # clicks 'x' icon ale.dismiss();
ale = driver.switch_to_alert(); # clicks 'x' icon ale.text;
A confirmation box is the second kind of alert; it displays a dialog with the OK and Cancel button. The confirmation box informs the developer about user choice whether the user pressed OK or Cancel.
confirm() method returns true if the user clicked "OK", and false otherwise('X' icon and 'Cancel') to the developer.
We can handle the Confirmation box in selenium python like an alert box, there is no coding difference.
Prompt is used to get value from the user in text format. Prompt provides text bar for user input; Prompt is rarely used alert type.
Prompt also follows the same coding as alert and prompt except the sendkeys method, and we can send a text to prompt text bar using the sendkeys() method in alerts API.
driver.get("https://chercher.tech/java/practice-pop-ups-selenium-webdriver"); driver.find_element_by_name("prompt").click(); ale = driver.switch_to_alert(); ale.send_keys("chercher.tech");
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.