CSS Locator c contains () InvalidSelectorException using Selenium WebDriver

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

The goal is to get a link About Googleon a Gmail page to practice CSS locators .

Here is the code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

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 following 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 checked and was able to find the element in the Selenium IDE using the same locator.

I read somewhere that the method findElement()returns a DOM node, and the code expects a WebElement object.

If so, is there a way around / casting?

Any suggestions?

+4
source share
3 answers

CssSelector , selenium IDE.

: , gmail.. , http://seleniumtrainer.com/. .

+1

:

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

css contains() Selenium WD - . .

contains() Xpath.

Xpath :

//a [ ((), " Google" )]

:

driver.findElement(By.xpath( "//a [ (()," Google ")]" ));

Selenium :

driver.findElement(By.linkText( " " ));

CSS Xpath:

  • css (Xpath xpath)
  • contains ( xpath).

BTW
Xpath Firefox:

+11

, , , Css Selector . " About Google , css. jQuery.

You can use a selector based on the value of the href attribute, as shown below, and it will work fine.

 #footer-list a[href*='about']

and use it like

WebElement aboutGoogle = driver.findElement(By.cssSelector("#footer-list a[href*='about']"));
0
source

All Articles