androidwebdriverselenium-webdrivertestautomationfx

Having difficulty in finding Elements using Xpath and CSS in Selenium Android Webdriver Testing


I want to automate android web apps using Selenium WebDriver and i've run a simple program to open the google page and search a term . While finding the element with the name and id it runs perfectly. But while trying to find the element with the Xpath and Css seems difficult. Does anybody know how to use xpath and css path in selenium android webdriver? Here is the sample code i've used:

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

}

Solution

  • I have managed to prove that By.xpath and By.cssSelector are able to find elements which can then use in our code to interact with the web page. For a couple of practical reasons I created a shadow, simplified test page which then submits a query to obtain search results from Google's search engine.

    Here is the simplified test page, enough to demonstrate the basics. Copy this file to the sdcard of your android device or AVD e.g. using the following command 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>
    

    And here's the modified version of the code in your question:

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

    I happen to be using JUnit 4 as the test runner (hence the @Test annotation) however this code should also work in JUnit 3.

    Points to note: