CSS Locator with contains()使用Selenium WebDriver的InvalidSelectorException

San*_*bra 6 java selenium css-selectors selenium-webdriver

我正在学习Selenium Webdriver并尝试编写一个简单的测试脚本.

目的是获取Gmail页面About Google上的链接,以便练习CSS定位器.

这是代码:

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();          
    }    
}
Run Code Online (Sandbox Code Playgroud)

我得到以下提到的例外:

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
Run Code Online (Sandbox Code Playgroud)

我已经检查过并且能够使用相同的定位器在Selenium IDE中找到该元素.

我在某处读到该findElement()方法返回一个DOM节点,并且代码期望一个WebElement对象.

如果是这种情况那么,是否有变通/铸造?

有什么建议?

naz*_*art 19

主要问题是在这一行:

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

csscontains()支持Selenium WD - 见这里.

使用contains()时必须使用Xpath.

使用Xpath,您的定位器将是:

// a [包含(text(),'关于Google')]

对于司机,它将如下:

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

要查找与Selenium的链接,您可以使用:

driver.findElement(By.linkText("你的链接名称在这里"));

Xpath相比,它是CSS选择器的限制:

  • 你不能使用css选择器的父元素(Xpath有xpath轴)
  • 你不能使用contains(它只是xpath特权).

BTW
为了从页面处理 Xpath定位器,您可以使用Firefox浏览器的扩展:

  • 实际上,在css中“包含”是通过*=来完成的,例如[attribute*='value'] 类似地,^=和$=分别表示开始和结束。 (2认同)
  • @JonNelson 我误解了你的意思。你能展示一些与问题情况相关的示例用法吗?用于替换此 xpath - `//a[contains(text(), 'About Google')]` (2认同)
  • 我注意到 Selenium 在内部将 `By.cssSelector("div[data-testid ^='avatar']")` 转换为 `By.xpath("//div[contains(data-testid,'avatar')]") ` (2认同)

小智 5

CssSelector 在脚本中不起作用,但在 selenium IDE 中起作用。

在 gmail 等网站上工作也不好。