Advanced Selenium

Handling Popups

In Selenium 2(WebDriver), testing popup windows involve switching the driver to the popup window and then running the corresponding actions. Twist recorder records actions in popup windows as commented code.

For eg.


      //Write your logic to locate the appropriate popup before using commented actions.
      //Look at - 'How do I handle popup in WebDriver' section for more details.
      //action in popup "Google". popup.findElement(By.name("q")).sendKeys("Thoughtworks");
      //action in popup "Google". popup.findElement(By.name("btnG")).submit();"
      

The above code is the result of recording in the popup window having google search page, searching for "Thoughtworks".

 

To get the above code working:

1) Identify the popup,

The following code identifies the popup window with title "Google". Note that the actions tells the title of the popup window. Add the code just before the first popup action being commented.


      String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
      WebDriver popup = null;
      Iterator<String> windowIterator = browser.getWindowHandles();
      while(windowIterator.hasNext()) { 
        String windowHandle = windowIterator.next(); 
        popup = browser.switchTo().window(windowHandle);
        if (popup.getTitle().equals("Google") {
          break;
        }
      }
      

2) Uncomment code for the same popup,


      //action in popup "Google". 
      popup.findElement(By.name("q")).sendKeys("Thoughtworks");
      //action in popup "Google". 
      popup.findElement(By.name("btnG")).submit();"
      

3) After the popup actions, switch the driver back to the parent window,


      browser.close(); // close the popup.
      browser.switchTo().window(parentWindowHandle); // Switch back to parent window.      

 

Working with Table Selenium - Dice.com

//Automation of Dice

 

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.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


public class DiceWebSite {


    private final static By byAdvancedSearch = By.linkText("Advanced Job Search");
    private final static By byJobTitle = By.id("excludeValueList1");
    private final static By byFindJobs = By.id("submit1-button");
    private final static By byState = By.id("STATE_LIST");
    private final static By byTableObj = By.xpath("//table[@class='summary']");
    private final static By byTBody = By.xpath("tbody");
    private final static By byTr = By.xpath("tr");
    private final static By byTd = By.xpath("td");

   

 

      public static void main(String[] args) throws InterruptedException {
       

      //Launching driver and Dice.com

       WebDriver driver;
        FirefoxProfile fp = new FirefoxProfile();
        driver = new FirefoxDriver(fp);
        driver.get("http://www.dice.com/");

 

        //Clicking on advanced search on dice.com

        driver.findElement(byAdvancedSearch).click();

 

       // Webdriver wait to synchronize 
        WebDriverWait wait = new WebDriverWait(driver,10);
        wait.until(ExpectedConditions.presenceOfElementLocated(byJobTitle));
        driver.findElement(byJobTitle).sendKeys("Testing");

       

       Thread.sleep(1000);

       

       //Using the select class to select and deselct dropdown values

       //can perform multiselect using select class
        Select selState = new Select(driver.findElement(byState));
        selState.selectByValue("AL");
        selState.selectByValue("AK");
        selState.deselectAll();
        selState.selectByValue("CO");
        Thread.sleep(1000);


        driver.findElement(byFindJobs).click();


        wait.until(ExpectedConditions.presenceOfElementLocated(byTableObj));
        driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);

       

 

        //Working with Table
        WebElement Table = driver.findElement(byTableObj);
        WebElement TBody = Table.findElement(byTBody);
        List<WebElement> trObjects = TBody.findElements(byTr);
        System.out.println(trObjects.size());
        for(WebElement WebEleTr:trObjects){
            List<WebElement> tdObjects = WebEleTr.findElements(byTd);
            for(WebElement WebEleTd:tdObjects){
                System.out.println(WebEleTd.getText());


                if(WebEleTd.getText().contains("Software")){
                    break;
                }
               }
            }

 

        //Closing the driver

        driver.close();
        }

}

 

Using CSS Selector - Google.com

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.firefox.FirefoxProfile;


public class CssSelector {

    public static void main(String[] args) {
        WebDriver driver;

 

        //Firefox Profile
        FirefoxProfile fp = new FirefoxProfile();
        fp.setEnableNativeEvents(true);
        fp.setAcceptUntrustedCertificates(true);
        driver = new FirefoxDriver(fp);

 

        //using CssSelector
        driver.get("https://www.google.com/?gws_rd=ssl");
        WebElement element = driver.findElement(By.cssSelector(".gbqfif"));

 

       //Css properties
        System.out.println(element.getCssValue("color"));
        element.sendKeys("bharath");

 

        //Css Selection for ID
        driver.findElement(By.cssSelector(".gbqfb")).click();
    }
}

Take Screenshot Function

    //Takes screenShot if needed
    public String getScreenShot() throws IOException {
        File screenShot;
        if (driver instanceof TakesScreenshot){
            screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        }
        else {
            // for Selenium Grid
            WebDriver augmentedDriver = new Augmenter().augment(driver);
            screenShot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        }
        String fileName = UUID.randomUUID().toString().substring(0,18).toUpperCase()+".png";
        String path=System.getProperty("output.directory")+"/images/"+fileName;

        // Needs Commons IO library
        FileUtils.copyFile(screenShot, new File(path));

        return "images/"+fileName;
    }

Launch Different Browsers

 //Constructor
    public SeleniumDriverUtil(String browserType){

     try {
         String fileName = System.getProperty("user.dir");
         if (browserType == "FireFox") {

             //Create a firefox profile
             FirefoxProfile fp = new FirefoxProfile();
             fp.setEnableNativeEvents(true);
             fp.setAssumeUntrustedCertificateIssuer(true);

             //launch the driver
             driver = new FirefoxDriver(fp);
             assert driver != null;
         }

         //If the browser Type is Internet Explorer Browser
         else if ((browserType == "InternetExplorer")) {

             //Set the setting to clean cache
             DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
             capabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
             capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
             capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);

             //Call the file name and Load IE Driver
             fileName += "/Resources/IEDriverServer.exe";
             File file = new File(fileName);
             System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
             driver = new InternetExplorerDriver(capabilities);
             assert driver != null;
         }
         //If the browser Type is chrome Browser
         else if ((browserType == "Chrome")) {
             fileName += "/Resources/chromedriver.exe";
             System.setProperty("webdriver.chrome.driver",fileName);
             driver = new ChromeDriver();
             assert driver != null;
         }

         //By default call firefox
         else {
             FirefoxProfile fp = new FirefoxProfile();
             fp.setEnableNativeEvents(true);
             driver = new FirefoxDriver();
             assert driver != null;
         }
     }
     catch(Exception e){
         System.out.printf(e.getMessage());
        }
    }

Kill Browser - using driver and Task Manager

 //Kills the IE Driver
    public void killDriver(String browserType) {
        final String KILL = "taskkill /F /IM ";
        if (browserType == "FireFox") {
            try {
                driver.close();
                Runtime.getRuntime().exec(KILL + "firefox.exe");
                System.out.println("Driver Closed");
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
        else {
            try {
                Runtime.getRuntime().exec(KILL + "iexplore.exe");
                Runtime.getRuntime().exec(KILL + "IEDriverServer.exe");
            } catch (Exception e) {
                System.out.println(e);
                //throw e;
            }
        }

Reading from Excel

public class ExcelUtil {

    private static ArrayList arrayListRowTestData= new ArrayList();

    public static ArrayList ExcelTestDataRead() throws IOException {
        try {
            String fileName = System.getProperty("user.dir");
            fileName += "/Resources/Excel.xlsx";
            FileInputStream file = new FileInputStream(fileName);

            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            while(rowIterator.hasNext()) {
                ArrayList arrayListColumnTestData= new ArrayList();
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while(cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch(cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            boolean valueBoolean = cell.getBooleanCellValue();
                            arrayListColumnTestData.add(String.valueOf(valueBoolean));
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            double valueDouble = cell.getNumericCellValue();
                            arrayListColumnTestData.add(String.valueOf(valueDouble));
                            break;
                        case Cell.CELL_TYPE_STRING:
                            String valueString  = cell.getStringCellValue();
                            arrayListColumnTestData.add(valueString);
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            arrayListColumnTestData.add(null);
                            break;
                    }
                }
                arrayListRowTestData.add(arrayListColumnTestData);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return arrayListRowTestData;
    }
}

JavaScript Executor

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * Created by bs211w on 9/8/2014.
 */
public class SeleniumTestClass {

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.facebook.com/r.php?locale=en_US");
        Thread.sleep(3000);
        JavascriptExecutor js = (JavascriptExecutor) driver;
        driver.findElement(By.id("u_0_0")).sendKeys("&");
        js.executeScript("document.getElementById(\"u_0_0\").value = \"test&\";");
    }
}

Backend Compatibility

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * Created by bs211w on 9/8/2014.
 */
public class SeleniumTestClass {

 

    public static void main(String[] args) {
        Selenium selenium = new DefaultSelenium(
                "localhost", 4444, "*firefox", "http://www.yoursite.com");
        selenium.start();

        WebDriver driver = new FirefoxDriver();

        Selenium seleniumWebDriver = new WebDriverBackedSelenium(driver, "http://www.yoursite.com");
    }
}

Selenium Grid - Differnt Browsers

http://localhost:4444/grid/console - Check the Status


Step 1: Start the hub

java -jar selenium-server-standalone-2.42.2.jar -role hub

 

Step 2:  Start the node
java -jar selenium-server-standalone-2.42.2.jar -role node 

 

Firefox Connection

 

java -jar selenium-server-standalone-2.42.2.jar -role webdriver -hub http://localhost:4444/grid/register -port 5556 -browser browserName=firefox

 

DesiredCapabilities capability = DesiredCapabilities.firefox();

capability.setBrowserName("firefox");
capability.setPlatform(Platform.VISTA);

 

IE - Connection

 

java -jar selenium-server-standalone-2.42.2.jar -role webdriver -hub http://10.0.9.42:4444/grid/register -port 5558 -browser browserName="internet explorer",version=8.0,platform=WINDOWS -Dwebdriver.ie.driver=C:\Users\bs211w

\Desktop\SAD\IEDriverServer.exe

 

DesiredCapabilities capability = DesiredCapabilities.internetExplorer();

capability.setBrowserName("iexplore");
capability.setPlatform(Platform.VISTA);
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

 

Chrome Connection

 

java -jar selenium-server-standalone-2.42.2.jar -role webdriver -hub http://10.0.9.42:4444/grid/register -port 5559 -browser browserName="chrome",version=8.0,platform=WINDOWS -Dwebdriver.chrome.driver=C:\Users\bs211w\Desktop

\SAD\chromedriver.exe

 

DesiredCapabilities capability = DesiredCapabilities.chrome();

capability.setBrowserName("chrome");

capability.setPlatform(Platform.VISTA);

 

 

//Program to Launch

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;

public class MainClass {

    public static void main(String[] args) {
        try {
            DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
            capability.setBrowserName("iexplore");
            capability.setPlatform(Platform.VISTA);

            WebDriver driver = new RemoteWebDriver(new URL("http://10.0.9.42:5558/wd/hub"), capability);
            driver.get("https://www.google.com/?gws_rd=ssl");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }


}

Print Print | Sitemap
© 2016 Automation Learn. All rights reserved.