CSS Locator with contains() InvalidSelectorException using Selenium WebDriver

CssSelector does not work in scripting but it works in selenium IDE.

It's also not good to work on sites like gmail.


The main problem is at this line:

driver.findElement(By.cssSelector("a:contains('About Google')"));

css doesn't maintain contains() for Selenium WD - See here.

For using contains() you have to use Xpath.

With Xpath your locator will be:

//a[contains(text(), 'About Google')]

and for driver it will be as:

driver.findElement(By.xpath("//a[contains(text(), 'About Google')]"));

For finding links with Selenium you can use:

driver.findElement(By.linkText("your link name here"));

It is limitation of CSS selectors compare to Xpath:

  • you can't take parent element with CSS selectors (Xpath has XPath axes)
  • you can't use contains (it is only XPath privilege).

BTW
For processing Xpath locators from page you able to use extension for Firefox browser:

  • FirePath

  • Xpath Checker