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

我正在学习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(); } } 

我得到以下提到的例外:

 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 

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

我读到某个地方, findElement()方法返回一个DOM节点,代码期望一个WebElement对象。

如果是这种情况那么,是否有解决方法/铸造?

有什么建议么?

包含文本的CssSelector在脚本中不起作用,但它在selenium IDE中有效。

还有一点是,在gmail这样的网站上工作并不好……你可以通过http://seleniumtrainer.com/中的组件来学习。 它有利于启动。

谢谢

主要问题在于这一行:

driver.findElement(By.cssSelector(“a:contains(’About Google’)”));

css不维护Selenium WD的contains() – 见这里 。

对于使用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浏览器的扩展:

  • FirePath

  • Xpath Checker

好的,因为Exception清楚地说明这里的问题是你的Css选择器无效。 ‘你试图根据它的文本获得About Google锚标记,这不是一个有效的css选择器 ‘。 它更像是一个jQuery选择器。

您可以使用基于href属性值的选择器,如下所示,它将正常工作。

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

并使用它

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