我想使用Selenium WebDriver自动化android web应用程序,我已经运行了一个简单的程序来打开google页面并搜索一个术语。在查找具有名称和id的元素时,它运行得很好。但是,在尝试使用Xpath和Css查找元素时,似乎很困难。有人知道如何在selenium android webdriver中使用xpath和css路径吗?下面是我使用的示例代码:
public class TestDriver extends TestCase
{
public static void testGoogle() throws Exception
{
AndroidDriver driver = new AndroidDriver();
driver.get("http://google.com");
WebElement element = driver.findElement(By.name("q"));
//WebElement element = driver.findElement(By.xpath("//*[@id='gbqfq']"));
//WebElement element = driver.findElement(By.cssSelector("#gbqfq"));
element.sendKeys("android driver");
element.submit();
System.out.println("Page title is: " + driver.getTitle());
//driver.quit();
}
}
我已经设法证明了By.xpath
和By.cssSelector
能够找到可以在我们的代码中使用的元素来与网页交互。出于几个实际原因,我创建了一个影子简化的测试页面,然后提交查询以从Google的搜索引擎获取搜索结果。
这里是简化的测试页面,足以演示基本知识。使用以下命令将此文件复制到android设备或AVD的SD卡上。html/sdcard/form。html代码>
<html>
<head>
<title>WebDriver form test page</title>
</head>
<body>
<form name="testform" action="http://www.google.co.uk/search" method="get">
<input id="gbqfq" class="gbqfif" type="text" value="" autocomplete="off" name="q">
<input type="submit" value="search Google">
</form>
</body>
</html>
下面是您问题中代码的修改版本:
@Test
public void testByClauses() throws Exception {
AndroidDriver driver = new AndroidDriver();
// driver.get("http://www.google.co.uk/");
driver.get("file:///sdcard/form.html");
System.out.println(driver.getPageSource());
WebElement nameElement = driver.findElement(By.name("q"));
WebElement xpathElement = driver.findElement(By.xpath("//*[@id='gbqfq']"));
WebElement cssElement = driver.findElement(By.cssSelector("#gbqfq"));
nameElement.sendKeys("android ");
xpathElement.sendKeys("driver ");
cssElement.sendKeys("webdriver");
nameElement.submit();
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
我碰巧使用JUnit 4作为测试运行程序(因此使用了@test注释),但是这段代码也应该在JUnit 3中工作。
注意事项:
sendKeys(...)
调用都会将文本附加到搜索查询By(...)
子句的工作原理,但是很高兴看到代码执行并获得一些匹配的搜索结果。AndroidDriver()
的本地构建实例。
对我有好处。
//Author: Oleksandr Knyga
function xPathToCss(xpath) {
return xpath
.replace(/\[(\d+?)\]/g, function(s,m1){ return '['+(m1-1)+']'; })
.replace(/\/{2}/g, '')
.replace(/\/+/g, ' > ')
.replace(/@/g, '')
.replace(/\[(\d+)\]/g, ':eq($1)')
.replace(/^\s+/, '');
}