2013-04-03 56 views
2

我想自動使用硒的webdriver的Android網絡應用程序,我已經運行一個簡單的程序打開谷歌頁面和搜索項的元素有困難。找到具有名稱和ID的元素時,它可以完美運行。但是試圖用Xpath和Css查找元素似乎很困難。有誰知道如何在selenium android webdriver中使用xpath和css路徑嗎?下面是示例代碼中,我使用:找到使用XPath和CSS中硒的Android webdriver的測試

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(); 
    } 

} 

回答

1

我已成功地證明By.xpathBy.cssSelector能找到的元素,然後可以在我們的代碼中使用與網頁互動。一對夫婦的實際原因我創建了一個影子,簡化測試頁,然後提交查詢,以獲得來自谷歌的搜索引擎的搜索結果。

下面是簡單的測試頁,足以證明的基本知識。將此文件複製到您的android設備或AVD的sdcard,例如使用以下命令adb push form.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

注意要點:

  • 我特意用3個獨立的WebElements這指的是相同的底層的HTML元素
  • 每個sendKeys(...)調用追加文本搜索查詢
  • 技術上講,我們並不需要提交的搜索查詢證明By(...)條款工作,但是它的很高興看到代碼執行並獲得一些匹配的搜索結果。
  • 我註釋掉加載谷歌搜索主頁上的要求,但它留在我的答案,所以你可以很容易地看到如何使用的,而不是靜態的HTML頁,在谷歌網站。
  • 我跑測試與本地連接的Nexus 4手機,通過USB,以及所使用的AndroidDriver()的當地建造實例。
+0

感謝Ripon Al Wasim提供的解決方案,我正在尋求解決方案 – Rajeshwaran

0

對我的作品好。

//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+/, ''); 
}