Selenium WebDriver By.cssSelector Element Locators With Example

WebDriver support many different element locating methods and locating element by it's CSS Path is one of the most popular way in webdriver software automation testing tool. If you not want to use by id, name, tag name, class name or link text as your locator then you can locate that element on page of software web application by it's CSS path. Read this tutorial to learn different ways of writing CSS path for any software web application's page element. You can get CSS path of any
element using selenium IDE software testing tool too by setting CSS as your Locator Builders Preference and then performing some action on that element in Selenium IDE software testing tool's recording mode. You can get CSS path of any element by Firebug too.

Now let we learn how we can use By.cssSelector in webdriver. Look in to bellow given image.


Here we can locate input box First name using bellow given webdriver syntax.

driver.findElement(By.cssSelector("input[name='fname']"));

Bellow given example will locate input box by CSS Selector to type text in it.
Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.
(Note : @Test method is marked with pink color in that example).

@Test
 public void test() 
  {
   driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
   driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("My Name");;//Locate element by cssSelector and then type the text in it.
  }

3 comments: