You can control the browser in Selenium Java according to user input by incorporating interactive prompts in your Java code. This typically involves using the Scanner
class to capture input from the console (such as “open” or “close”) and then perform actions like launching or closing the browser based on that input.
Step-by-Step Approach
1. Import Required Classes
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Scanner;
2. Capture User Input and Control the Browser
package org.example; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); WebDriver driver = null; System.out.println("Type 'open' to launch browser or 'exit' to quit:"); String command = scanner.nextLine(); if ("open".equalsIgnoreCase(command)) { // Initialize ChromeDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); System.out.println("Browser opened."); System.out.println("Type 'close' to close browser:"); String closeCmd = scanner.nextLine(); if ("close".equalsIgnoreCase(closeCmd) && driver != null) { driver.quit(); // Closes all browser windows System.out.println("Browser closed."); } } else if ("exit".equalsIgnoreCase(command)) { System.out.println("Exiting program."); } else { System.out.println("Unknown command."); } scanner.close(); } }
- Make sure you have the Selenium Java bindings and ChromeDriver set up in your project.
- You may need to set the ChromeDriver executable path using
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver")
if it’s not in your system PATH.
3. How It Works?
- The program prompts the user to type a command.
- If the user enters “open,” it creates a new Chrome browser session.
- After opening, it waits for the user to type “close” and then shuts down the browser using
quit()
. - If “exit” is entered at the start, the program ends.
- This pattern can be extended to support other browsers or actions.
Key Methods Used
Method | Description | Syntax |
---|---|---|
new ChromeDriver() | Launches a new Chrome browser window | WebDriver driver = new ChromeDriver(); |
driver.quit() | Closes all browser windows and ends session | driver.quit(); |
Tips
- This console-based approach is ideal for demo or learning purposes. In real test automation, these decisions are usually handled by test code and not manual input.
- Always handle exceptions and ensure resources like the browser and scanner are closed properly to avoid resource leaks.
By combining Selenium WebDriver with Java’s standard input mechanisms, you can dynamically open and close browsers based on user commands during runtime.