CSS selectors for Selenium with example

 When we don't have an option to choose Id or Name, we should prefer using CSS
locators as the best alternative.
 CSS stands for Cascading style sheet
 This language is used to show the look and formatting of documents written in
markup language such in HTML or XML
 CSS pattern matching principles are being used to located element on webpage for
further operations.
 CSS has more Advantage than XPath.
 CSS selectors are much faster and simpler than the XPath.
 In CSS selector we can move in forward direction while in XPath is bidirectional.
Due to this CSS selector is faster than XPath
 Selenium’s By class also provide cssSelector() method to locate element using CSS
Selector
 In IE XPath works very slow, where as CSS works faster when compared to XPath.
Syntax:
TagName[AttributeName=AttributeValue]
Example 1: input[id=email]
Example 2: input[name=email][type=text]
In CSS there are two special characters which has important role to play.
1. Hash (#) refers to Id
Example: css=input[id=email] - The above one can be re-written as
css=input#destination
2. dot (.) refers to class.
Syntax: css=input.submitbtn

Some basic CSS Selector
 By using Absolute path
 By using relative path
 By using Class Selector
 By using ID selector
 By using attributes selectors
 By using attributes name selectors
 By using Pattern matching
 Nth-child

CSS selector by using absolute path
<html>
<body>
<form name="loginForm">
<label for="username">UserName: </label>
<input type="text" name="username" for="wow" /><br/>
<label for="password">Password: </label>
<input type="password" name="password" /><br/>
<input name="login" type="submit" value="Login" />
</form>
</body>
</html>
 Absolute path of username text field would be
$$(“html>body>form>input:nth-of-type(1)”)
Then in selenium we could find the username text field by using this line of code
WebElement username =
driver.findElement(By.cssSelector(“html>body>form>input:nth-of-type(1)”));
 Relative path
$$(“input[name=username]”)
WebElement username = driver.findElement(By.cssSelector(“input[name=username]”));

Finding CSS selector using class selector
In general we have class as one attribute to HTML tags through which we normally reach to
web-element on webpage. So CSS selector syntax would be
[HTML][dot][value of class attribute]
Or
[dot][value of class attribute]
If HTML source code is
<input type="text" class="username" for="wow" /><br/>
Then CSS Selector should be Input.username
Line of WebDriver code used to do action on this element would be
WebElement username = driver.findElement(By.cssSelector(“input.username”));

Finding CSS Selector using ID selector
Like Class, Id attribute is also used to find any element uniquely. In this case CSS selector
syntax would be
[HTML tag][hash][value of attribute]
Or
[hash][value of attribute]
If HTML source code would be
<input type="text" id="username" for="wow" /><br/>
Then line of WebDriver code would be
WebElement username = driver.findElement(By.cssSelector(“input#username”));
Or
WebElement username = driver.findElement(By.cssSelector(“#username”));

Finding CSS selector using various attributes
If HTML source code would be
<input type="text" id="username" for="wow" /><br/>
Then CSS selector would be Input[id=username]
Line of Webdriver code would be
WebElement username = driver.findElement(By.cssSelector(“input#username”));

Pattern Matching
Syntax for Starts with in CSS selector is ^= , CSS Selector would be written like this
Input[id^=‘user’]
Then it will return input tag with attribute id starting with user.
Syntax for Ends with in CSS selector is $= , CSS Selector would be written like this
Input[id$=‘name’]
Then it will return input tag with attribute id ending with name word.
Syntax for contains text with in CSS selector is *= , CSS Selector would be written like this
Input[id*=‘name’]
Then it will return input tag with attribute id containing name word in its value.

Nth-child[index]
Syntax: *:nth-child[index]
By using this we can find any child of a parent using index of that element.
There is another method used in CSS selector is :nth-of-type[index]
But this not supported in selenium webdriver.

CSS locator Examples using ID and Class attributes

/* below syntax will find "input" tag node which contains "id=email" attribute */
css=input[id=email]
In selenium we can write it as
WebElement Email = driver.findElement(By.Css("input[id=email]"));
Email.SendKeys("hello@sampleemail.com");

You can make use of Selenium IDE to verify if the identifier is working fine or not. If the
element has identified, it will highlight the field and html code in Yellow color.
Please find the below screen shot with example:
css selector 1

/*below syntax will find "input" tag which contains "id=email" and "type=text" attribute.*/

css=input[name=email][type=text]
Please find the below screen shot with example:
single elements

/*Below is the syntax for using input Tag and class attribute: It will find input tag which
contains "submitButton" class attribute.
css=input.rc-button.rc-button-submit
If you observe the above, there are two classes defined in one class is rc-button and the
other class is rc-button-submit. We can combine two class in css by using dot(.) symbol.

Please find the below screen shot with example:
single elements

Using CSS locators, we can also locate elements with sub-strings. Which are really help full
when there are dynamically generated ids in webpage
There are there important special characters:
1. '^' symbol, represents the starting text in a string.
2. '$' symbol represents the ending text in a string.
3. '*' symbol represents contains text in a string.

CSS Locators for Sub-string matches(Start, end and containing text) in selenium
/*It will find input tag which contains 'id' attribute starting with 'ema' text. Email starts
with 'ema' */

css=input[id^='ema']
If you remove the symbol an try to find the element with same sub-string, it will display
error as "locator not found". We can observe the error in the below screen shot. one with
error and the other with success
starting substring

/*It will find input tag which contains 'id' attribute ending with 'ail' text. Email ends with
'mail' */
css=input[id$='mail']
Please find the below screen shot with example:
ending substring

/* It will find input tag which contains 'id' attribute containing 'mai' text. Email contains
'mai' */
css=input[id*='mai']
CSS Element locator using child Selectors

/* First it will find Form tag following remaining path to locate child node.*/
css=form>label>input[id=PersistentCookie]
Please find the below screen shot with example:
single elements

CSS Element locator using adjacent selectors
/* It will try to locate "input" tag where another "input" tag is present on page. the below
example will select third input adjacent tag.

css=input + input + input

XPath
In XPath the starting point is called the context node.
Absolute XPath
Absolute XPath starts with the root node or a forward slash (/).
The advantage of using absolute is, it identifies the element very fast.
Disadvantage here is, if any thing goes wrong or some other tag added in between, then this
path will no longer works.

Example:
If the Path we defined as
1. html/head/body/table/tbody/tr/th
If there is a tag that has added between body and table as below
2. html/head/body/form/table/tbody/tr/th
The first path will not work as 'form' tag added in between

Relative XPath
 A relative xpath is one where the path starts from the node of your choice - it
doesn't need to start from the root node.
 It starts with Double forward slash(//)
Syntax:
//table/tbody/tr/th
 Advantage of using relative xpath is, you don't need to mention the long xpath, you
can start from the middle or in between.
 Disadvantage here is, it will take more time in identifying the element as we specify
the partial path not (exact path).

If there are multiple elements for the same path, it will select the first element that is
identified