While using Selenium WebDriver for automated testing of web applications I have found it difficult to learn how to specify locators for WebElements. This article presents example HTML, CSS selectors, and WebDriver Java code to help you write your automated tests more quickly. Use specific CSS selectors to make your tests more reliable when the user interface changes.
You can save the attached HTML file, CssSelectorsTest.html, and Java file, CssSelectorsTest.java, and run the WebDriver test. You'll have to add the Selenium jar, change the code to use the WebDriver of your choice, and change the path to the HTML file.
I'll give you an overview of these CSS selectors.
If your HTML element has a unique id,
<a id="create-registerFreePopup" class="button ghost" href="https://www.google.com/?q=create+a+project">Create a Project</a>
this is the simplest way to select it.
By.id("create-registerFreePopup")
When you don't have an id, use CSS selectors like the following.
.h1Class selects any type of element with class="h1Class".
form > input.textClass selects the input element with attribute class="textClass" which is an immediate child of the form element.
div.divClass input.textClass selects the input element with attribute class="textClass" which is a child/grandchild/great-grandchild/... of the div element with attribute class="divClass".
#checkboxId.checkboxClass selects the element with id="checkboxId" and class="checkboxClass". Use this when you have an ID, but it's not unique.
input[name='checkboxName' selects the input element with name="checkboxName".
input[value^='radioThis'] selects the input element which has a name which starts. with "radioThis"
input[value^='radioThis'] selects the input element which has a name which starts. with "radioThis"
input[type='radio']:checked selects the input element with attribute type="radio" which is checked (i.e. selected).
h1 selects the h1 element.
input:last-child selects the input element which is the last child of a parent element.