使用Selenium WebDriver的java CSS定位器,带有contains()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对象
如果是这种情况,是否有解决方案/铸造
有什么建议吗
# 1 楼答案
主要问题在这条线上:
css
不为Selenium WD-See here维护contains()
要使用
contains()
,必须使用Xpath使用Xpath时,您的定位器将是:
对于驾驶员,它将是:
要查找Selenium的链接,您可以使用:
与Xpath相比,CSS选择器的局限性是:
顺便说一句
要处理页面中的Xpath定位器,您可以使用Firefox浏览器的扩展:
FirePath
Xpath Checker