Selenium:Are you ready to use CSS selectors with selenium?
2012-11-23 09:25:02   来源:   评论:0 点击:

Nowadays CSS selectors become popular and took place of xpath selectors. While locating elements the ideal candida...

Nowadays CSS selectors become popular and took place of xpath selectors. While locating elements the ideal candidate is to reference elements on the page by their unique id or name. If that is not possible, incase not available or auto generated, then XPath or CSS are the strategies available to you. Here you can get answer on Why CSS Locators are the way to go vs XPath.

One useful tool I found is FirePath which is a Firebug extension that adds a development tool to edit, inspect and generate XPath 1.0 expressions, CSS 3 selectors and JQuery selectors (Sizzle selector engine). The problem with fire path generates xpath specific to element but for css or Sizzle it is not always specific to selected element.

Selenium IDE 1.0.11
released on 30/May/2011 has inbuilt CSS locator builder! Selenium IDE will now create locators using CSS when recording. Also, same as getXpathCount, new command getCssCount added to count the number of nodes that match the specified css selector. So now using css selector you can get number of nodes that match the specified selector.

Sizzle, used by selenium as CSS selector engine, provides Positional and Form Selector Additions makes locator simpler and more readable, for instance:

  • :nth(index_0_base)

    Simplified position selector (li:nth(5) finds the 6th li element)

  • :input

    Finds all input elements including textarea, select and button.

  • :text
  • :checkbox
  • :file
  • :password
  • :submit
  • :image
  • :reset
  • :button


    that finds the input element with the specified input type.
    Here :button also finds button elements in addition to input elements having type button.

You can find more details for additional selectors in Sizzle documentation.

I had documented some examples for defining complex CSS and X-Path selector.


X Path






locate first divelement

By id



Locate div with id eleid

By class




locate div with class nameeleclass if more than one class exist then xpath 2 will be used

By attribute

//div[@title='Move mouse here']

  1. div[title=Move mouse here]
  2. div[title^=Move]
  3. div[title$=here]
  4. div[title*=mouse]

you can use match operators for class and id as well, for example div[id^=menu-item]




div#eleid >*

div#eleid >h1




div h1 

Will work for //div/*/…../h1

By index



6th li element

By content

//a[contains(.,'Issue 1164')]

a:contains(Issue 1164)

Case Sensitive

By Child

  1. //li[a[contains(.,'Issue 1244')]]
  2. //*[./a[contains(.,'Issue 1244')]]
  3. //ul[.//a[contains(.,'Issue 1244')]]
  1. li{a:contains(Issue 1244)}
  2. ul{a:contains(Issue 1244)}

<ul><li> Improv

相关热词搜索:Selenium selectors webdriver CSS

下一篇:Selenium - CSS Selector

分享到: 收藏