CSS Selector Cheat Sheet - aclaudio123/selenium-tutorial GitHub Wiki

CSS Selector Cheat Sheet

It's important to know that not every element on a page would have a static id, unique name, unique link text etc. For those elements without unique identifiers, we need to build customized CSS selectors or XPath to find and perform actions on them. Whatever we use, it should always be unique and find one matching node unless we want to capture a list of elements.

CSS

Syntax: 

tag[attribute='value']

Example:

input[id='displayed-text']

input[class='displayed-class']

you can use the # and . as shortcut to find id and class attributes respectively

“#” -> Id

“.” -> Class

#displayed-text
input#displayed-text

.displayed-class
input.displayed-class

We can append multiple class values until we find a unique element (order doesn't matter)

.class1.class2.class3

Using wildcards in CSS Selectors:

  • "^" -> Represents the starting text
  • "$" -> Represents the ending text
  • "*" -> Represents the text contained
Syntax:

tag[attribute<special character>='value']

Examples:

input[class='inputs'] -> get input node(s) with attribute=class attribute_value='inputs'

input[class^='inputs'] -> get input node(s) with attribute=class attribute_value starts with 'inputs' 

input[class='displayed-class']
input[class$='class'] -> get input node(s) with attribute=class attribute_value ends with 'class' 
input[class*='displayed-class'] -> input node(s) with attribute=class attribute_value contains 'displayed-class'

Finding Children

fieldset

fieldset>table -> direct child of fieldset called table

fieldset>#product -> fieldset child with id='product'

fieldset>button -> direct child of fieldset called button

fieldset>a
fieldset>input#name -> fieldset child called input with id='name'

For more CSS tips:

http://saucelabs.com/resources/articles/selenium-tips-css-selectors