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')"));
css
不contains()
支持Selenium WD - 见这里.
使用contains()
时必须使用Xpath.
使用Xpath,您的定位器将是:
// a [包含(text(),'关于Google')]
对于司机,它将如下:
driver.findElement(By.xpath("// a [contains(text(),'About Google')]"));
要查找与Selenium的链接,您可以使用:
driver.findElement(By.linkText("你的链接名称在这里"));
与Xpath相比,它是CSS选择器的限制:
BTW
为了从页面处理 Xpath定位器,您可以使用Firefox浏览器的扩展: