เราสามารถค้นหาอิลิเมนต์ด้วย Locator CSS Selector ใน Selenium WebDriver นิพจน์ทั่วไปสำหรับสร้าง CSS Expression คือ tagname[attribute='value'] เราสามารถใช้ attribute id และ class เพื่อสร้าง CSS ได้
กับ id ไวยากรณ์คือ tagname#id ตัวอย่างเช่น input#txt-loc โดย input คือ tagname และ txt-loc คือค่าของ id attribute
กับ class name ไวยากรณ์คือ tagname.class ตัวอย่างเช่น input.txt-cls โดย input คือ tagname และ txt-cls คือค่าของ class attribute
หากมี n sub-elements (children) ของ web element element (parent) และเราต้องการค้นหา nth-child ไวยากรณ์คือ nth-of-type(n)

ใน HTML ข้างต้น หากต้องการค้นหา li ที่ 4 ของ parent ul คือ anchor element ที่มีข้อความ "Questions and Answers" CSS จะเป็น ul.reading li:nth-of-type(4) ส่วนการระบุ last child จะเป็น ul.reading li:last-child
สำหรับ attribute ที่มีค่า dynamic เราสามารถใช้สัญลักษณ์ ^= เพื่อระบุ element ที่ค่า attribute เริ่มต้นด้วยข้อความเฉพาะ เช่น input[name^='qa1']
ใช้สัญลักษณ์ $= สำหรับค่า attribute ที่ลงท้ายด้วยข้อความเฉพาะ เช่น input[class$='loc']
ใช้สัญลักษณ์ *= สำหรับค่า attribute ที่มี substring เฉพาะ เช่น input[name*='sub']
ตัวอย่างโค้ด Selenium (Java)
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();
}
}