CSS selectors and selenium (webdriver)

When I started automation with selenium, I started using xpath, because that was the way to go. Till, when I moved companies, there was this talk of other QA engineers relying on CSS for locating elements from the DOM. I have recently started using CSS locators for various reasons. You can read about it here

I have been basing a lot of my locators on these very cool links

1. Are you ready to use CSS with selenium?
2. Multiple classes and ID’s, CSS- trips and tricks.
3. CSS selectors demystified from Sauceio 
4. Multiple classes and CSS by Maxdesign
5. Can I use this ?  Search
6. Css Rosetta stone and cookbook.
7. And my favorite of all, convert your Xpath to CSS using this link here.[cssify]

Some examples:-

  1. Spaces in classnames: So if you have a class name like this ul class=”A B”, you can do a ul.A.B
  2. Lists can be tricky: Here’s a pointer:
	<li class="shrUPGrid">
           <ul id="sfly_5" class=" shrSG shrSGSelect">
<ul>
	<li style="background-image: <span class=;">url(https://sphotos-a.xx.fbcdn.net.jpg)"></li>
</ul>
<ul>
	<li style="background-image: <span class=;">url(https://sphotos-a.xx.fbcdn.net.jpg)"></li>
</ul>

You can find the Li by

 findElement(By.cssSelector("li.shrUPGrid > ul > li:nth-of-type(""
							+ pictureIndex + ")")).click(); 

where pictureindex is the index of the li

If I am sounding all cryptic please don’t hesitate to drop me a line.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s