-
Download and install the Java Development Kit (JDK) from the Oracle website. You need the JDK to be able to compile and run Java programs.
-
Download the Selenium Java client library from the Selenium website. This library contains the classes and methods that you will use to control the browser with Selenium.
-
Add the Selenium Java library to your project's classpath. In Eclipse, you can do this by right-clicking on your project, selecting "Build Path" and then "Add External Archives".
-
Download the ChromeDriver executable from the ChromeDriver website. Make sure to download the version that is compatible with your version of Chrome.
-
Add the ChromeDriver executable to your system's PATH. This will allow you to use the ChromeDriver executable from any location on your system.
-
Import the necessary Selenium classes in your Java code. For example, to create a ChromeDriver instance, you would import the following classes:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
- Create an instance of the ChromeDriver class. For example:
WebDriver driver = new ChromeDriver();
That's it! You're now ready to use Selenium WebDriver in your Java code to control the Chrome browser.
Here is a simple example that demonstrates how to use Selenium to open a web page, navigate to a link, and print the page title:
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumExample {
public static void main(String[] args) {
// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();
// Navigate to the Google homepage
driver.get("http://www.google.com");
// Find the search box element and enter a search query
driver.findElement(By.name("q")).sendKeys("selenium");
// Find the search button and click it
driver.findElement(By.name("btnK")).click();
// Wait for the search results to load
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
// Print the page title
System.out.println(driver.getTitle());
// Close the browser
driver.quit();
}
}