Monday, November 1, 2010

Selenium with CSS locators.

XPath locator is one of the most quirky and one of the most precise locator. This disadvantage is clearly seen while running the tests under IE while Firefox works with xpath pretty well. This problem is related to internal browser features in particular to the libraries being used for elements location definition. But this is another story. The main thing is that tests which intensively use XPath work extremely slow under IE and this feature is the cause of huge variety of problems related to execution speed as well as quality of the tests itself especially during operations with dynamic content. For this reason CSS locators can be good alternative of XPath.
What can we do with CSS locators?

First of all,
CSS locators also give the ability to describe object hierarchy. For instance, the XPath locator like:
Xpath=//div//span/a

can be described via
CSS in the following way:
css=div * span > a

From the sample above we may see analogy for XPath and
CSS namely:
a) Character "/"  meaning next level of
DOM hierarchy corresponds to CSS operator ">".
b) Character "//" meaning any object hierarchy level under current object corresponds to
CSS operator "*".

Secondly, just like XPath, the
CSS locators can locate object by thier attribute values. For example the locator like:
Xpath=//div[@id="some_id"]

can be described via
CSS in the following way:
css=div[id=some_id]

Also there\'s abitity to check for partial attribute value matching. But
CSS locators are a little bit limited in this area. There\'s ability to verify that attribute value consists of several space-separated words but one word equals to some value. It means that the XPath locator like:
xpath=//div[contains(@title,"title")]

can be expressed via
CSS like:
css=div[@title~=title]

Both the locators can detect the element like 

<div title="some multiword title" />  while the element like  <div title="my_title" />
  
can\'t be detected by CSS locator from above.

Also
CSS has simplified form for some attributes. For instance, the element having the id attribute like  <div id=some_id /> can be located by the following CSS:
css=div#some_id

In addition to that
CSS locators have specific way to define the object by the class attribute. The XPath locator like:
xpath=//div[@class="myclass"]

has the following
CSS analog:
css=div.myclass

Such features make
CSS suitable in some cases.

 More details about CSS can be found by the forllowing URL: http://www.w3.org/TR/CSS2/selector.html

So, in some cases CSS locators are the analogs of XPath locators with one serious advantage: CSS works fast no matter what the browser we use.

Of course,
CSS locators have their own limitations like: problems to locate objects by index, problem to locate objects higher in the object hierarchy or so.

3 comments: