CSS Locator with contains() InvalidSelectorException using Selenium WebDriver

34,473

Solution 1

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

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

Solution 2

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:

Share:
34,473
Sandeep Dharembra
Author by

Sandeep Dharembra

Updated on July 16, 2022

Comments

  • Sandeep Dharembra
    Sandeep Dharembra almost 2 years

    I am learning Selenium Webdriver and trying to write a simple test script.

    The intent is to get the About Google link on Gmail page so as to practice CSS locators.

    Here is the code:

    public class GoogleSearch {
        
        public static void main(String[] args) {            
            WebDriver driver = new FirefoxDriver();         
            driver.get("https://www.gmail.com");
            
            WebElement aboutGoogle = driver.findElement(By.cssSelector("a:contains('About Google')"));          
        
            driver.close();
            driver.quit();          
        }    
    }
    

    I get the below-mentioned exception:

    Exception in thread "main" org.openqa.selenium.InvalidSelectorException: The given selector a:contains('About Google') is either invalid or does not result in a WebElement. The following error occurred:
    InvalidSelectorError: An invalid or illegal selector was specified
    Command duration or timeout: 356 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
    Build info: version: '2.45.0', revision: '32a636c', time: '2015-03-05 22:01:35'
    System info: host: 'XXXXX', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-49-generic', java.version: '1.7.0_79'
    *** Element info: {Using=css selector, value=a:contains('Need')}
    Session ID: 0f1869f8-c59a-4f61-b1c7-b34ada42573f
    Driver info: org.openqa.selenium.firefox.FirefoxDriver
    

    I had checked and was able to find the element in Selenium IDE using the same locator.

    I read somewhere that the findElement() method is returning a DOM node and the code is expecting a WebElement object.

    If this is the case then, is there a workaround/casting?

    Any suggestions?