Using CSS to identify Elements


Using CSS to identify Elements

To identify the Element in the webpage Selenium uses the locators to search and match the elements.
Selenium uses the below locators to identify the element on webpage

Identifier
Id
Name
Link
DOM
XPath
CSS
UI-element

We can use Id / name if the element has id / name defined in the code, if the element is not having id / name then the solution to identify the element is xpath / css.

XPath locator is mostly used to identify the element. But this has a disadvantage of slowness in identifying the element if the hierarchy is very large

For this reason CSS locators are good alternative instead of XPath.

CSS locator will give you clear picture of your element hierarchy 

Below are some of the differences we can find between xpath and css

Xpath
Css
//div
Div
//
*
/
> 
@id
#
@class
.
@name
Name
@title
Title

Examples:
1.
Xpath =//div//table/a
Css=div*table>a

2.
Xpath=//input[@name=’login’]
Css=input[name=’login’]

3.
Xpath=//input[@class=’userid’]
Css=input.userid

4.
Xpath=//table[@id=’gridSorce’]/tr
Css=table#gridSource>tr


CSS use the prefix / suffix chars for Sub-String matches.

^=
Match a prefix
$=
Match a suffix
*=
Match a substring


5.
Xpath=//div[@title='selenium automation testing']

For the above css can be like
div[title=selenium automation testing]
div[title^=selenium]
div[title$=testing]
div[title*=automation]


6.
Xpath=//div[@id='eleid']//h1
Css= div h1

7.
Xpath=//table[contains(@title,'sales')]
Css=table[containts~=sales]


Exaple :  open google, type selenium and click search

import com.thoughtworks.selenium.DefaultSelenium;

public class google
{
  public static void main(String args[]) throws Exception
  {
   DefaultSelenium ds=new DefaultSelenium("localhost",4444,"*firefox","http://");
   ///open the given url
   ds.start();
   ds.Windowmaximise();
   ds.open("www.google.co.in");
   Thread.sleep(5000);
   ds.type("css=input#gbqfq","selenium");
    s.click("css=input#gbqfb");
  }
}



Comments