Locating Web Elements with CSS Selectors in Selenium: A Practical Guide
Learn how to efficiently locate web elements using CSS selectors in Selenium. This tutorial focuses on tag and class selectors, providing practical examples and demonstrating how to target specific elements on a webpage for automated testing and browser automation.
Locating Web Elements with CSS Selectors
Understanding CSS Tag and Class Selectors
This section explains how to find specific elements on a webpage using CSS selectors, specifically the tag and class methods. Finding elements involves inspecting their HTML code. Let's use a textbox example:
- Open the webpage: Go to https://www.testandquiz.com/selenium/testing.html
- Inspect the element: Right-click on the "Automation Testing" checkbox and select "Inspect Element" (or similar, depending on your browser).
- Identify the tag and class: Note the HTML tag (e.g., `input`) and the value of its "class" attribute (e.g., "Automation").
In Java, using Selenium, you'd locate this element like so:
driver.findElement(By.cssSelector("Tag.Value of Class attribute"))
For the "Automation Testing" checkbox, this translates to:
driver.findElement(By.cssSelector("input.Automation"))
Example: Locating a Checkbox with CSS Selector
Here's a sample Java script showing how to use a CSS selector to locate and interact with the checkbox. The comments explain each step.
Java Code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SampleTwo {
public static void main(String[] args) {
// System Property for Gecko Driver
System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
// Initialize Gecko Driver using Desired Capabilities Class
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
WebDriver driver= new FirefoxDriver(capabilities);
// Launch Website
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
// Locate the checkbox by cssSelector and check it using click() function
driver.findElement(By.cssSelector("input.Automation")).click();
// Close the Browser
driver.close();
}
}
This script demonstrates how to use the CSS selector to locate the checkbox and then perform an action (clicking it) using Selenium. Remember to adjust the `webdriver.gecko.driver` path to your own GeckoDriver location.