CSS Locator with contains() InvalidSelectorException using Selenium WebDriver

后端 未结 3 832
情深已故
情深已故 2021-02-04 16:17

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

The intent is to get the About Google link on

相关标签:
3条回答
  • 2021-02-04 16:54

    Well as the Exception is clearly stating the problem here is that your Css Selector is not valid. 'You are trying to get the About Google anchor tag based on it's text which is not a valid css selector'. It's more of a jQuery selector.

    You could use the selector based on the value of 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 讨论(0)
  • 2021-02-04 16:59

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

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

    0 讨论(0)
  • 2021-02-04 17:09

    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

    0 讨论(0)
提交回复
热议问题