Selenium tricks for CSS and Xpath locators

            Selenium tricks for CSS and Xpath locators

In this post you will learn some CSS rules and how to use CSS selectors and Xpath locators in Selenium.

(1) Id:
An element's id is defined as "[@id='idName']" in Xpath but "#idName" in CSS.
For example, a 'div' element with id 'panel' will be represented as below:
In Xpath locator 
?
1
//div[@id='panel']
In CSS selector
?
1
css=div#panel

(2) Class:
An element's class is defined as "[@class='className']" in Xpath but ".className" in CSS.  
For example, a 'div' element with class 'panelClass' will be represented as below:
In Xpath locator 
?
1
//div[@class='panelClass']
In CSS selector
?
1
css=div.panelClass
For element with multiple class we need to separate with space(" ") in Xpath and dot(".") in case of CSS. See below example,
In Xpath locator 
?
1
//div[@class='panelClass1 panelClass2']
In CSS selector
?
1
css=div.panelClass1.panelClass2

(3) Any Attributes:
For selecting an element by its any of the attribute(say "name" is an attribute of a 'div' element and "type" in an "input" element) is given below: 
In Xpath locator 
?
1
//div[@name='continue']
?
1
//input[@type='button']
In CSS selector
?
1
css=div[name='continue']
?
1
css=input[type='button']

(4) Direct Child:
A direct child of an element is denoted as "/" in Xpath and ">" in CSS selector. See the example below for a direct child "li" for a "ul" element:
In Xpath locator 
?
1
//ul/li
In CSS selector
?
1
css=ul > li

(5) Child or Subchild:
A direct child of an element is denoted as "//" in Xpath and a wehite-space(" ") in CSS selector. See the example below for a child/subchild "li" for a "ul" element:
In Xpath locator 
?
1
//ul//li
In CSS selector
?
1
css=ul li
Note that "ul li" and "ul > li" are different. If you are confusing please go through this article.

(6) nth Child:
For finding 'nth' child, in Xpath we denote as "[n]" and in CSS we denote as ":nth-of-type(n)". See the below example,
?
1
2
3
4
5
6
7
<ol id="drinks">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
  <li>Soup</li>
  <li>Soft Drinks</li>
</ol>
In Xpath locator 
?
1
//ul[@id='drinks']/li[5]
In CSS selector
?
1
css=ul#drinks li:nth-of-type(5)
Also you can use ":nth-child" but the difference between ":nth-child" and ":nth-of-type(n)" is:
li:nth-child(2)
This means, select an element if It is a paragraph element and the second child of a parent.

li:nth-of-type(2)
This means, select the second paragraph child of a parent. This is less conditional.

See here for more details on difference between the above two.

If we want to select the "fifth li element" (Soft Drinks) in this list, we can use the nth-of-type, which will find the fifth li in the list.
?
1
css=ul#drinks li:nth-of-type(5)
On the other hand, if we want to get the "fifth element" only if it is a li element, we can use a filtered nth-child which will select again (Soft Drinks) here.
?
1
css=ul#drinks li:nth-child(5)
(7) Parent of an element:
Parent of an element can be represented as "/.." in Xpath and ":parent" in CSS selectors. For example, if you want to indicate parent of the list item of class 'blue'
?
1
2
3
4
5
6
7
<ul>
  <li class="blue">first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>fifth</li>
</ul>
In Xpath locator 
?
1
//li[@class='blue']/..
In CSS selector
?
1
css=li.blue:parent

(8) Next Sibling:
Next sibling is nothing but next adjacent element which is inside the same parent on the page. An adjacent sibling combinator selector allows you to select an element that is directly after another specific element. For example, If you want to select the sibling of "li" element with class "blue" which is 'second' list item, 
In Xpath locator 
?
1
//li[@class='blue']/../li[2]
In CSS selector
?
1
css=li.blue + li
Similarly, if you want to indicate 'third' list item, see the below
In Xpath locator 
?
1
//li[@class='blue']/../li[3]
In CSS selector
?
1
css=li.blue + li + li

(9) Match by Innertext:
There is a javascript methodcontains() which can be used to check the inner text of a web element. For example a link with text "Sign in"
In Xpath locator 
?
1
//a[contains(text(),'Sign in')]
or 
?
1
//a[contains(string(),'Sign in')]
In CSS selector
?
1
css=a:contains('Sign in')

(10) Match by Sub-string:
This is interesting and is described below. With this we can match strings with its partial text. E.g. prefix, suffix or any pattern(sub-string)
(i) Match a Sub-string(pattern):
Taking an example of a 'div' with an 'id' that contains the text "pattern"
?
1
2
3
<div id="someText_pattern_someOtherText">
...
</div>
In Xpath locator, we need to use "contains()" to match a sub-string
?
1
//div[contains(@id,'pattern')]
In CSS selector, we need to use "*=" for matching a sub-string
?
1
css=div[id*='pattern']

(ii) Match a prefix:
Taking an example of a 'div' with an 'id' that starts with the text "prefixString"
?
1
2
3
<div id="prefixString_pattern_someOtherText">
...
</div>
In Xpath locator, we need to use "starts-with" to match a prefix
?
1
//div[starts-with(@id,"prefixString")]
In CSS selector, we need to use "^=" for matching a prefix
?
1
css=div[id^='prefixString']

(iii) Match a suffix:
Taking an example of a 'div' with an 'id' that starts with the text "suffixString"
?
1
2
3
<div id="prefixString_pattern_sufixString">
...
</div>
In Xpath locator, we need to use "ends-with" to match a suffix Note that "ends-with()" is a standard XPath 2.0 function only, it won't work if you are using Xpath 1.0 engine 
?
1
//div[ends-with(@id,"suffixString")]
In CSS selector, we need to use "$=" for matching a suffix
?
1
css=div[id$='suffixString']
The summary of sub-string match is listed out in the following table:
Match a Sub-stringMatch a PrefixMatch a Suffix
Xpathcontains()starts-with()ends-with()
CSS*=^=$=

How to Identify Web Elements Using Selenium Xpath

              Using Xpath as a Locator


Xpath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being mark up languages and since they fall under the same umbrella, xpath can be used to locate HTML elements.
The fundamental behind locating elements using Xpath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.
Xpath can be created in two ways:
Relative Xpath
Relative Xpath begins from the current location and is prefixed with a “//”.
For example: //span[@class=’Email’]
Absolute Xpath
Absolute Xpath begins with a root path and is prefixed with a “/”.
For example: /html/body/div/div[@id=’Email’]
Key Points:
  • The success rate of finding an element using Xpath is too high. Along with the previous statement, Xpath can find relatively all the elements within a web page. Thus, Xpaths can be used to locate elements having no id, class or name.
  • Creating a valid Xpath is a tricky and complex process. There are plug-ins available to generate Xpath but most of the times, the generated Xpaths fails to identify the web element correctly.
  • While creating xpath, user should be aware of the various nomenclatures and protocols.
Selenium Xpath Examples
Xpath Checker
Creating Xpath becomes a little simpler by using Xpath Checker. Xpath Checker is a firefox add-on to automatically generate Xpath for a web element. The add-on can be downloaded and installed like any other plug-in. The plug-in can be downloaded from “https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/”.
As soon as the plug-in is installed, it can be seen in the context menu by right clicking any element whose xpath we want to generate.
Click on the “View Xpath” to see the Xpath expression of the element. An editor window would appear with the generated Xpath expression. Now user has the liberty to edit and modify the generated Xpath expression. The corresponding results would be updated cumulatively.
Note that the Xpath Checker is available for other browsers as well.
But re-iterating the fact, that most of the times, the generated Xpaths fails to identify the web element rightly. Thus, it is recommended to create our own Xpath following the pre defined rules and protocols.
In this sample, we would access “Google” image present at the top of the login form at gmail.com.
Creating a Xpath of a web element
Step 1: Type “//img[@class=’logo’]” i.e. the locator value in the target box within the Selenium IDE.
Syntax: Xpath of the element
Step 2: Click on the Find Button. Notice that the image would be highlighted with yellow color with a florescent green border around the field.
Selenium Locators 12

How to Find XPath Using Firebug





steps

  1. Image titled Find XPath Using Firebug Step 1
    1
    Open Firefox browser with its Mozilla home page
    Ad
  2. Image titled Find XPath Using Firebug Step 2
    2
    Click on Bug tab at the right corner of the Browser.
  3. Image titled Find XPath Using Firebug Step 3
    3
    Click on Inspect element button and place your tip of cursor on any element for which you want to find XPath
  4. Image titled Find XPath Using Firebug Step 4
    4
    In this example, the Mozilla logo was selected. As soon as you hover your cursor on the Logo and click once on it, its HTML tag will get highlighted in Firebug
  5. Image titled Find XPath Using Firebug Step 5

    5
    Right Click on highlighted code and Select Copy XPath like this
  6. Image titled Find XPath Using Firebug Step 6
    6
    Now place this XPath in to your script

Handling Dynamic Elements in Selenium WebDriver

                       Handling Dynamic Elements in Selenium WebDriver Dynamic elements are those elements which have identifiers that a...