Selenium WebDriver: Locating Web Elements with CSS Selectors (Tag and Attribute)

Learn how to effectively locate web elements using CSS selectors that combine tag names and attribute values in Selenium. This tutorial demonstrates precise element selection, avoiding unintended elements, and improves the robustness of your automated testing scripts.



Selenium WebDriver: Locating Elements with CSS Selectors (Tag and Attribute)

Introduction to CSS Tag and Attribute Selectors

CSS selectors provide a flexible way to locate elements in web pages. Combining a tag name with an attribute selector lets you target elements based on both their type (tag) and a specific attribute value. This approach is more precise than using only the tag name, helping to avoid accidentally selecting the wrong element.

CSS Tag and Attribute Selector Syntax


tagname[attribute="value"]
      

This selector targets elements of type tagname that have the attribute attribute with the exact value value. You can use various HTML attributes like id, class, name, `type`, etc. The more specific your attribute selection, the better (to avoid selecting unintended elements).

Example: Locating Form Elements

Assume this HTML snippet (replace with your actual HTML):


<form>
  <input type="text" id="userName" />
  <input type="email" id="email" />
  <button type="submit" id="submitButton"/>
</form>
      

To locate the username input field using its ID:


input[id="userName"]
      

To locate the submit button using its ID:


button[id="submitButton"]
      

Using Tag and Attribute Selectors in Selenium (Illustrative)

(Illustrative example using Java with Selenium. Remember to replace `"path/to/geckodriver"` with the actual path and handle potential exceptions. Adapt the selectors to your page's HTML structure.)


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class CSSSelectorExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        WebDriver driver = new FirefoxDriver(capabilities);

        driver.get("https://www.example.com/myform"); //Replace with your URL

        WebElement userNameField = driver.findElement(By.cssSelector("input[id='userName']"));
        userNameField.sendKeys("TestUser");

        WebElement submitButton = driver.findElement(By.cssSelector("button[id='submitButton']"));
        submitButton.click();

        driver.quit();
    }
}
      

(The browser will open, the username will be entered, and the button will be clicked.  No specific console output is shown for this example.)