Selenium css selector

Selenium web element locating strategy using css selector.

Common css selector

  • Direct child using ">"
<div>
  <a>...</a>
</div>
css=div > a
  • Child or subchild using whitespace
<div>
  ...
    ...
      <a>...</a>
    ...
  ...
</div>
css=div a
  • Id using "#"
<div id='foo'>
  ...
    <a>...</a>
  ...
</div>
css=div#foo a
  • Class using "."
<div class="foo">
  ...
    <a>...</a>
  ...
</div>
css=div.foo a
  • All elements using "*"
<div id="foo">
  ...
</div>
css=div#foo > *
  • Next sibling using "+"
<form>
  <input id="username"></input>
  <input>...</input>
</form>
css=input#username + input
  • Following sibling using "~"
<form>
  <input id="username"></input>
  ...
  <input>...</input>
</form>
css=input#username ~ input
  • Attribute values using key=value
<form>
  <input name="username" type="text"></input>
  <input name="submit" type="button"></input>
</form>
css=input[name='username']
css=input[name='submit'][type='button']
  • Index of child using nth-xxx(n)
css=ul#foo li:nth-of-type(3)
css=ul#foo li:first-of-type
css=ul#foo li:last-of-type
css=ul#foo li:nth-last-of-type(3)
css=ul#foo li:nth-last-child(3)
css=ul#foo li:nth-child(3)
css=ul#foo *:nth-child(3)
css=ul#foo li:first-child
css=ul#foo li:last-child
css=ul#foo li:only-child
css=ul#foo li:only-of-type
css=ul#foo li:empty
css=ul#foo li:nth(2) # sizzle
  • Sub-string using special chars
1) start with:
css=div[id^='prefix']
2) ends with:
css=div[id$='suffix']
3) contains:
css=div[id*='substring'] #containing substring
css=div[id~='word']      #containing word
  • Inner text using contains
<div>
  <a>Log Out!</a>
</div>
css=div a:contains('Log Out') # sizzle
  • Negative using not (sizzle)
css=a.confirmation_link:not(.hidden)
css=.confirmation_link:not(div)
css=.submit_button:not(#clear_button)
css=input[type=button]:not(p#not_this_input > input)

References

css selenium webdriver automation