Monday, May 19, 2014

Css Selector Vs Xpath



10 down vote accepted
CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,
  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion
However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

If you know css selectors, those are much more easier (and will work fine with IE without any problem ) than xpath even though they can't replace entire xpath.


Consider below HTML tags


 <div id="firstDiv">This div tag has static id </div>

 <p id="paragraps_dynamic_1234">This p tag has dynamic id</p>

 <a onclick="doThat()" title="doThatOperation">This a tag has multiple attributes</a>

 <h1 name="heading1" value="headName">This is heading</h1>


<div>
<input type="text" id="username" name="username"
<input type="password" id="password" name="pwd"
</div>

<h2 id="propertyUserData">This tag is for starts-with example</h2>


Tag XPATH CSS SELECTOR
div "//div[@id='firstDiv']" "div[id='firstDiv']"
p "//p[contains(@id,'paragraps_dynamic_')]" "p[id*='paragraps_dynamic_']"
a "//a[contains(@onclick,'doThat') and @tile='doThatOperation']" "a[onclick*='doThat'][tile='doThatOperation']"
h1 "//h1[@name='heading1' and @value='headName']" "h1[name='heading1'][value='headName']"
input "//div/input[@id='username']" "div > input[id='username']"
input "//h2[starts-with(@id,'propertyUser')]" "h2[id^='propertyUser']"

By seeing above locators we can conclude some points regarding css selectors

  • Using css selector we can access particular node or immediate child of any node
  • Can combine as many conditions as we want for single node.
  • Can achieve starts-with, contains functionality using ^,* symbols respectively. 
  • We can't traverse back using css selector.
  • We can't go to  the siblings also (preceding as well as following)

No comments:

Post a Comment