Selenium CSS Selectors Examples

SeleniumAutomation TestingTesting Tools

 We can locate elements with locator CSS Selector in Selenium webdriver. The general expression to create a CSS expression is tagname[attribute='value']. We can utilize the id and class attributes to create a CSS.

With id, the syntax of a CSS expression is tagname#id. For instance, for a CSS expression - input#txt-loc, input is the tagname and the txt-loc is the value of the id attribute.

With class name, the syntax of a CSS expression is tagname.class. For instance, for a CSS expression - input.txt-cls, input is the tagname and the txt-cls is the value of the class attribute.

If there are n sub-elements(children) of a webelement element(parent), and we want to locate the nth child, the syntax of a CSS expression is nth-of –type(n).

In the above html, if we want to locate the fourth li of the parent ul i.e the anchor element having the text - Questions and Answers, the CSS should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the CSS should be ul.reading li:last-child.

For attributes having dynamic values, we can use symbol ^= to identify an element whose attribute value begins with a specific text. For example, input[name^='qa1'] [here input is the tagname and the value of the name attribute begins with qa1].

For attributes having dynamic values, we can use symbol $= to identify an element whose attribute value ends with a specific text. For example, input[class$='loc'] [here input is the tagname and the value of the class attribute ends with loc].

For attributes having dynamic values, we can use symbol *= to identify an element whose attribute value has a specific substring. For example, input[name*='sub'] [here input is the tagname and the value of the name attribute contains the substring sub].

Code Implementation

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 CSSLocator{
   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(10, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      //identify element
      WebElement m = driver.
      findElement(By.cssSelector("input[id='session_key']"));
      //enter text
      m.sendKeys("Java");
      String s = m.getAttribute("value");
      System.out.println("Attribute value: " + s);
      //close browser
      driver.close();
   }
}

Output

raja
Published on 25-Jun-2021 13:23:50
Advertisements