SELENIUM : How do I handle prompts (input dialogs) in Selenium?

Опубликовано: 15 Сентябрь 2024
на канале: SDET Automation Testing Interview Pro
1k
27

SELENIUM : How do I handle prompts (input dialogs) in Selenium?

SDET Automation Testing Interview Questions & Answers

We will be covering a wide range of topics including QA manual testing, automation testing, Selenium, Java, Jenkins, Cucumber, Maven, and various testing frameworks.

SELENIUM : How do I handle prompts (input dialogs) in Selenium?

To handle prompts or input dialogs in Selenium, you can use the `Alert` class provided by the WebDriver API. Prompts are similar to alerts but require user input before accepting or dismissing them. Here's how you can handle prompts using Selenium WebDriver:

1. Switch to the prompt: Use the `switchTo().alert()` method to switch the WebDriver's focus to the prompt dialog.

Alert prompt = driver.switchTo().alert();

2. Enter text into the prompt: Use the `sendKeys()` method of the prompt to enter text into the input field of the prompt.

prompt.sendKeys("Your input");

3. Accept or dismiss the prompt: Once you have entered the text, you can accept the prompt (click on the "OK" button) or dismiss it (click on the "Cancel" button) using the `accept()` or `dismiss()` methods, respectively.

// Accept the prompt
prompt.accept();

// Dismiss the prompt
prompt.dismiss();

Note: It's important to handle prompts within a try-catch block since an `UnhandledAlertException` may occur if a prompt is not present when you attempt to switch to it.

Here's an example code snippet:

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PromptExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("

// Switch to the prompt
Alert prompt = driver.switchTo().alert();

// Enter text into the prompt
prompt.sendKeys("Your input");

// Accept the prompt
prompt.accept();

driver.quit();
}
}

In the above example, we switch to a prompt on the page, enter text into the prompt, and then accept it.

Ensure that you have the appropriate WebDriver initialized and the necessary dependencies imported in your project.