How to find an element using the “CSS Selector” in Selenium?

SeleniumAutomation TestingTesting Tools

We can find an element using the css locator with Selenium webdriver. To identify the element with css, the expression should be tagname[attribute='value'].

We can also specifically use the id attribute to create a css expression.

With id, the format of a css expression should be tagname#<id>. For example,input#txt [here input is the tagname and the txt is the value of the id attribute].

With class, the format of css expression should be tagname.<class> . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute].

If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n).

In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child.

For attributes whose values are dynamically changing, we can use ^= to locate an element whose value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa].

For attributes whose values are dynamically changing, we can use $= to locate an element whose value ends with a particular text. For example, input[class$='txt'] [here input is the tagname and the value of the class attribute ends with txt].

For attributes whose values are dynamically changing, we can use *= to locate an element whose value contains a specific sub-text. For example, input[name*='nam'] [here input is the tagname and the value of the name attribute contains the sub-text nam].

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorCss{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      //identify element with css
      WebElement n = driver.
      findElement(By.cssSelector("input[id='session_key']"));
      n.sendKeys("Java");
      String str = n.getAttribute("value");
      System.out.println("Attribute value: " + str);
      driver.quit();
   }
}

Output

raja
Published on 06-Apr-2021 08:43:32
Advertisements