Monday, 18 February 2013

Common WebDriver API



Input Text Field
HTML –
<p class="label">Login Name<br />
<input type="text" name="tl_login" id="login" size="32" maxlength="30" />
</p>
<p class="label">Password<br />
<input type="password" name="tl_password" size="32" maxlength="32" />
</p>
API –
  • Finding Elements
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@id='login']"));
tlElement=driver.findElement(By.cssSelector("#login"));
tlElement=driver.findElement(By.name("tl_login"));
tlElement=driver.findElement(By.id("login"));
  • Operation on Input Box
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.sendKeys("admin");
String lname=tlElement.getTagName();
String lname=tlElement.getAttribute("value");
tlElement.clear();
Example – Example6.java 
//Script of verify input text field

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example6
{
    static WebDriver driver;
    public static void main(String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        WebDriverWait wdw = new WebDriverWait(driver, 7);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']")));
        element.sendKeys("admin");
        System.out.println(element.getAttribute("value"));
        element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_password']")));
        element.sendKeys("admin");
        System.out.println(element.getAttribute("value"));
        driver.close();
    }
}
 

Buttons
HTML –
<input type="submit" name="login_submit" value="Login" />
API –
  • Finding Element
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@name='login_submit']"));
tlElement=driver.findElement(By.cssSelector("input[name="login_submit"]"));
tlElement=driver.findElement(By.name("login_submit"));
  • Operation on Buttons
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.click();
String lname=tlElement.getTagName();
String lname=tlElement.getAttribute("value");
Example – Example7.java
//Script of verify buttons
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example7
{
    static WebDriver driver;
   
    public static void main(String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        WebDriverWait wdw = new WebDriverWait(driver, 7);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']")));
        element.sendKeys("admin");
        System.out.println(element.getAttribute("value"));
        element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_password']")));
        element.sendKeys("admin");
        System.out.println(element.getAttribute("value"));
        element=driver.findElement(By.xpath("//input[@name='login_submit']"));
        element.click();
        driver.switchTo().defaultContent();
        driver.switchTo().frame("titlebar");
        driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
        driver.close();
    }
}
 

Links
HTML –
<p>
<a href="firstLogin.php">New User?</a><br />
<a href="lostPassword.php">Lost Password?</a>
</p>
<p>
TestLink project <a href="http://testlink.sourceforge.net/docs/testLink.php">Home</a><br />
TestLink is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU GPL</a>
</p>
API –
  • Find Link Elements
List<WebElement> MyList = driver.findElements(By.tagName("a"));
MyList .get(i).getText() – Get text of links
MyList.get(i).getAttribute("href") – Get links
  • Find a Particular Link
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("////a[contains(text(),'Home')]"));
tlElement=driver.findElement(By.linkText("Home"));
  • Operation on Links
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.click();
String lname=tlElement.getTagName();
Example - Example8.java
//Script of verify links
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example8
{
    static WebDriver driver;
   
    public static void main(String args[])
   
{
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        WebDriverWait wdw = new WebDriverWait(driver, 7);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']")));
        List<WebElement> all_links=driver.findElements(By.tagName("a"));
        int count=all_links.size();
        for(int i=0;i<count;i++)
        {
            String linkname=all_links.get(i).getAttribute("href");
            System.out.println(linkname);
        }
       
        driver.close();
    }
}

Moving Between Frames
HTML –
<frame src="lib/general/navBar.php" name="titlebar" scrolling="no" noresize="noresize" />
<frame src="lib/general/mainPage.php" scrolling='auto' name='mainframe' />
API –
driver.switchTo().frame("mainframe");
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
Example - Example9.java
//Script of verify Selection box
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Example9
{
    static WebDriver driver;
   
    public static void main(String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']"));
        element.sendKeys("admin");
       
element = driver.findElement(By.xpath("//input[@name='tl_password']"));
        element.sendKeys("admin");
        element=driver.findElement(By.xpath("//input[@name='login_submit']"));
        element.click();
       
        driver.switchTo().frame("mainframe");
        List<WebElement>  options = driver.findElements(By.tagName("option"));
        System.out.println(options.size());
        for (WebElement option : options)
        {
            System.out.println(option.getText());
        }
        System.out.println("----------------------------------------");
        Select select=new Select(driver.findElement(By.xpath("//select[@name='docs']")));
        options=select.getOptions();
        for (WebElement option : options)
        {
            System.out.println(option.getText());
        }
        select.selectByIndex(1);
     
   //driver.switchTo().defaultContent();
        //driver.switchTo().frame("titlebar");
        //driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
        //driver.close();
    }
} 

Selection Box
HTML –
<select class="menu_combo" style="font-weight:normal;" name="docs" size="1"
                onchange="javascript:get_docs,'http://localhost/testlink/');" >
                <option value="leer"> -Choose Document-</option>
                                            <option value="Configuration_of_FCKEditor_and_CKFinder.pdf">Configuration_of_FCKEditor_and_CKFinder.pdf</option>
                            <option value="customfields_for_computing_times.txt">customfields_for_computing_times.txt</option>
                            <option value="excel2TestLink.pdf">excel2TestLink.pdf</option>
                            <option value="glosary.html">glosary.html</option>
                            <option value="remote_execution_quick_start.txt">remote_execution_quick_start.txt</option>
                            <option value="samples.txt">samples.txt</option>
                            <option value="testlink_installation_manual.pdf">testlink_installation_manual.pdf</option>
                            <option value="testlink_user_manual.pdf">testlink_user_manual.pdf</option>
                            <option value="tl-bts-howto.pdf">tl-bts-howto.pdf</option>
                            <option value="tl-file-formats.pdf">tl-file-formats.pdf</option>
                            <option value="youtrack-readme.pdf">youtrack-readme.pdf</option>
                                                </select>
API –
List<WebElement>  options = driver.findElements(By.tagName("option"));
                                System.out.println(options.size());
        for (WebElement option : options)
        {
            System.out.println(option.getText());
        }
                                or
Select select=new Select(driver.findElement(By.xpath("//select[@name='docs']")));
                                options=select.getOptions();
                                for (WebElement option : options)
        {
                                                System.out.println(option.getText());
                                }

select.selectByVisibleText("-Choose Document-");
select.selectByIndex(1);
Example - See the above Example9.java script

Radio Button and Checkboxes
HTML –
<td>
<input type="checkbox" name="active"  checked="checked"  />Active</td>
</tr>
<tr>
<td></td><td>
<input type="checkbox" name="is_public"  checked="checked"/>Public</td>
</tr>
API –
  • Finding Elements
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement=driver.findElement(By.cssSelector("input[name=\"active\"]"));
tlElement=driver.findElement(By.name("active"));
  • Operation on Input Box
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.isSelected()
tlElement.click();
Example - Example10.java
 //Radio Buttons and Check Boxes
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example10
{
    static WebDriver driver;
  
    public static void main(String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
       
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']"));
        element.sendKeys("admin");
        element = driver.findElement(By.xpath("//input[@name='tl_password']"));
        element.sendKeys("admin");
        element=driver.findElement(By.xpath("//input[@name='login_submit']"));
        element.click();
      
        driver.switchTo().frame("mainframe");
      
        driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
        driver.findElement(By.xpath("//input[@name='create']")).click();
      
        
element=driver.findElement(By.xpath("//input[@name='active']"));
        if (element.isDisplayed())
        {
            System.out.println("checkbox found");
        }
        if (element.isEnabled())
        {
            System.out.println("checkbox is enabled");
        }
        if (element.isSelected())
        {
            System.out.println("Checkbox is selected");
        }
      
        element.click();
     
   driver.switchTo().defaultContent();
        driver.switchTo().frame("titlebar");
        driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
        driver.close();
    }

}

Handle Text Editable area –
HTML –
<tr>
<td>Project description</td>
<td style="width:80%"><input type="hidden" id="notes" name="notes" value="" style="display:none" /><input type="hidden" id="notes___Config" value="CustomConfigurationsPath=http://localhost/testlink/cfg/tl_fckeditor_config.js" style="display:none" /><iframe id="notes___Frame" src="http://localhost/testlink/third_party/fckeditor/editor/fckeditor.html?InstanceName=notes&amp;Toolbar=tl_default" width="100%" height="200" frameborder="0" scrolling="no"></iframe></td>
</tr>
API –
driver.switchTo().frame("notes___Frame");
WebElement editable = driver.switchTo().activeElement();
editable.sendKeys("Project for Selenium with Java with TestNG");
Example - Example11.java script
//Verify Text Area
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example11
{
    static WebDriver driver;
   
    public static void main(String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("http://localhost/testlink/login.php");
        WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']"));
        element.sendKeys("admin");
        element = driver.findElement(By.xpath("//input[@name='tl_password']"));
        element.sendKeys("admin");
        element=driver.findElement(By.xpath("//input[@name='login_submit']"));
       
element.click();
        driver.switchTo().frame("mainframe");
        driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
        driver.findElement(By.xpath("//input[@name='create']")).click();
       
        driver.switchTo().frame("notes___Frame");
        WebElement editable = driver.switchTo().activeElement();
        editable.sendKeys("TestLink Project for Selenium with Java");
       
        driver.switchTo().defaultContent();
        driver.switchTo().frame("titlebar");
        driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
        driver.close();
    }
}

Pop Up handle
API –
String parentWindowHandle = driver.getWindowHandle();
WebDriver popup = driver.switchTo().window("FileUpload");
popup.findElement(By.xpath("//input[@id='title']")).sendKeys("test");
popup.findElement(By.xpath("//input[@value='Cancel']")).click();
driver.switchTo().window(parentWindowHandle);
//Example - Example12.java script
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example12
{
    public static WebDriver driver;
    public static WebElement tlElement;
    public static void main (String args[])
    {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("http://localhost/testlink/index.php");
       
driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin");
        driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin");
        driver.findElement(By.xpath("//input[@name='login_submit']")).click();
       
        driver.switchTo().frame("mainframe");
        driver.findElement(By.xpath("//a[contains(text(),'Test Specification')]")).click();
        driver.switchTo().frame("treeframe");
        driver.findElement(By.cssSelector("#extdd-3")).click();
        driver.switchTo().defaultContent();
               
        driver.switchTo().frame("mainframe");
        driver.switchTo().frame("workframe");
        driver.findElement(By.xpath("//input[@value='Upload new file']")).click();
       
       
String parentWindowHandle = driver.getWindowHandle();
        System.out.println(parentWindowHandle);
        WebDriver popup = driver.switchTo().window("FileUpload");
        popup.findElement(By.xpath("//input[@id='title']")).sendKeys("test");
        popup.findElement(By.cssSelector("input[name=\"uploadedFile\"]")).sendKeys("C:\\file.jpg");//click();
        popup.findElement(By.xpath("//input[@value='Cancel']")).click();
        driver.switchTo().window(parentWindowHandle);
       
        driver.switchTo().defaultContent();
        driver.switchTo().frame("titlebar");
        driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
        driver.quit();
    }

}

Mouse hover example
API –
public static WebDriver driver;
public static WebElement mnuElement,subElement;
Actions builder = new Actions(driver); 
builder.moveToElement(mnuElement).perform();//Move the mouse on main menu to display the sub menu
Thread.sleep(2000);
builder.moveToElement(subElement);
builder.click().perform();//Click on the sub menu
//Example – Example13.java script
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import com.google.common.base.Function;

public class Example13
{
    public static WebDriver driver;
    public static WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
               
.withTimeout(50, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(new Function<WebDriver, WebElement>()
        {
            public WebElement apply(WebDriver driver)
            {
                return driver.findElement(locator);
            }
         }
                );
       
return  foo;
        };
    public static void main (String args[]) throws InterruptedException
    {
        driver=new FirefoxDriver();
        driver.get("http://shopping.indiatimes.com");
        WebElement element=fluentWait(By.xpath("//div/descendant::div[@id='shopbybrand']"));
       
        if (element.getText().equals("Shop by Brand"))
        {
            System.out.println("Element Found");
        }
       
element = driver.findElement(By.xpath("(//a[contains(text(),'More')])[2]"));
        Actions builder = new Actions(driver); 
        builder.moveToElement(element).perform();
        element=fluentWait(By.xpath("//a[contains(text(),'Nokia Shop')]"));
        builder.moveToElement(element);
        builder.click().perform();
        driver.quit();
    }
}

SELENIUM RC EMULATION
It is possible to emulate Selenium Remote Control (RC) using the WebDriver Java implementation on any of its supported browsers. This allows you to maintain both WebDriver and Selenium test assets side by side and to engage in an incremental migration from Selenium to WebDriver. In addition, running the normal Selenium RC server is not required.
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://www.google.com";
// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");
// Get the underlying WebDriver implementation back.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();
//Finally, close the browser.
selenium.stop();

No comments:

Post a Comment