Wednesday, 13 June 2018

WebDriver Initialization



Drivers Initialization (See Example1.java)

  • WebDriver Instance

// import the WebDriver Package
import org.openqa.selenium.WebDriver;
          //Create an instance of WebDriver
           WebDriver driver;

  • Initialize Firefox WebDriver
            Download the Geckodriver from the link - https://github.com/mozilla/geckodriver/releases
// import the FireFox WebDriver Package
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

//Create an instance of WebDriver backed by Firefox
FirefoxOptions ffoptions = new FirefoxOptions();
System.setProperty("webdriver.gecko.driver",
                "<Path Of Geckodriver>");
ffoptions.setCapability("marionette", true);
ffoptions.setCapability("acceptInsecureCerts", true);
driver = new FirefoxDriver(ffoptions);

  • Initialize Internet Explorer WebDriver

Download InternetExplorerDriver standalone server from http://code.google.com/p/selenium/downloads/list. The latest version is IEDriverServer_x64_3.12.0. Follow these steps to setup your tests for running with InternetExploreDriver:
1. Include the InternetExplorerDriver location in your PATH environment variable OR
2. Put the “IEDriverServer.exe “ under above created “lib” folder. Specify its location via the webdriver.ie.driver system property (see sample below)

//Imort the Internet Explore WebDriver Package
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;

//Create an instance of WebDriver backed by IE
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe")
InternetExplorerOptions ieoption = new InternetExplorerOptions();               ieoption.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
 ieoption.setCapability("requireWindowFocus", true);
  driver = new InternetExplorerDriver(ieoption);

  • Initialize Chrome WebDriver

Download chrome driver from http://code.google.com/p/chromedriver/downloads/list. The latest version is chromedriver_win_26.0.1383.0.zip.  Follow these steps to setup your tests for running with ChromeDriver:
1. Include the ChromeDriver location in your PATH environment variable OR
2. Put the “chromedriver.exe “ under above created “lib” folder . Specify its location via the webdriver.chrome.driver system property (see sample below)

// Import the Chrome WebDriver
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;

//Create an instance of WebDriver backed by Chrome
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
System.setProperty("webdriver.chrome.driver", “chromedriver.exe”);
driver = new ChromeDriver(options);


  • Initialize Safari WebDriver
           Safari driver is already available in latest Mac OS. Verify this (/usr/bin/safaridriver) should be available on your Mac OS.

// Import the Safari WebDriver
import org.openqa.selenium.safari.SafariOptions;
import  org.openqa.selenium.safari.SafariDriver;

//Create an instance of WebDriver backed bySafari
            SafariOptions safoption = new SafariOptions();
            safoption.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
           driver = new SafariDriver(safoption);

  • Initialize HtmlUnit WebDriver
// Import the HtmlUnit WebDriver
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

//Create an instance of WebDriver backed by HtmlUnit
WebDriver driver = new HtmlUnitDriver ()



Script – Example1.java
/* Script for verifying Drivers Initialization */
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example1
{
                public static WebDriver driver;
                public static void instantiateBrowser(BrowserType browserType, String url)
                {
                                    driver = getWebDriver(browserType);
                                    driver.get(url);
                                    closeBrowser();
                }
                                 
                public static void closeBrowser()
                {
                                    driver.quit();
                }
                public static WebDriver getWebDriver(BrowserType browserType)
                {
                                    switch (browserType)
                                    {
                                        case FIREFOX:
                                            driver=new FirefoxDriver();
                                            return driver;
                                        case IE:
                                                driver = new InternetExplorerDriver();
                                            return driver;
                                        case CHROME:
                                                //System.setProperty("webdriver.chrome.driver", "D:\\Applications\\Selenium\\chromedriver\\chromedriver.exe");
                                                driver = new ChromeDriver();
                                                CommonMethods.wait(10000);
                                            return driver;
                                        case HTMLUNIT:
                                                driver = new HtmlUnitDriver();
                                            return driver;
                                        default:
                                            throw new RuntimeException("Browser type unsupported");
                                    }
                }
                                 
                public enum BrowserType
                {
                                    FIREFOX, IE, CHROME, HTMLUNIT
                }
                public static void main (String args[])
                {
                                BrowserType brw=BrowserType.CHROME;
                                instantiateBrowser(brw,"http://google.co.in");
                }

}
 

Tuesday, 19 February 2013

WebDriver Page Interaction



Text Verification
There is no text verification methods (like isTextPresent()) available in webdriver. Use the below customized code to verify the text present on the page –

public static boolean verifyTextPresent(WebDriver wd,String text)
                {
                                return wd.getPageSource().contains(text);
                }
 Script Name - Example5.java
----------------------------------------------------------------------------
//Script of verify page text
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 Example5
{
    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']")));
        if (driver.getPageSource().contains("Login Name"))
        {
            System.out.println("Text Found");
        }
        driver.close();
    }
}

----------------------------------------------------------------------------
 
Page Interaction
Methods designed for interacting with the element in hand, WebElement also provides two methods allowing you to search for elements within the current element’s scope:
Method
Purpose
findElement(By by)
Finds the first element located by the provided method (see Locators table).
findElements(By by)
Finds all elements located by the provided method.
WebDriver offers for interacting with the elements on that page via its findElement methods. These methods accept an argument of type By, which defines several static methods implementing different means of element location:
Locators
Locator
Example (Java)
id attribute
By.id(“myElementId”)
name attribute
By.name(“myElementName”)
XPATH
By.xpath(“//input[@id=’myElementId’]”)
Class name
By.className(“even-table-row”)
CSS Selector
By.cssSelector(“h1[title]”)
Link Text
By.linkText(“Click Me!”)
By.partialLinkText(“ck M”)
Tag Name
By.tagName(“td”)
WebElement Methods
Method
Purpose
clear()
Clears all of the contents if the element is a text entity.
click()
Simulates a mouse click on the element.
getAttribute(String name)
Returns the value associated with the provided attribute name (if present) or null (if not present).
getTagName()
Returns the tag name for this element.
getText()
Returns the visible text contained within this element (including subelements) if not hidden via CSS.
getValue()
Gets the value of the element’s “value” attribute.
isEnabled()
Returns true for input elements that are currently enabled; otherwise false.
isSelected()
Returns true if the element (radio buttons, options within a select, and checkboxes) is currently selected; otherwise false.
sendKeys(CharSequence…
keysToSend)
Simulates typing into an element.
setSelected()
Select an element (radio buttons, options within a select, and checkboxes).
submit()
Submits the same block if the element if the element is a form (or contained within a form). Blocks until new page is loaded.
toggle()
Toggles the state of a checkbox element.
WebDriver provides a support class named Select to greatly simplify interaction with select elements and their association options:
Method
Purpose
selectByIndex(int index)/
deselectByIndex(int index)
Selects/deselects the option at the given index.
selectByValue(String value)/
deselectByValue(String value)
Selects/deselects the option(s) that has a value matching the argument.
selectByVisibleText(String text)/
deselectByVisibleTest(String text)
Selects/deselects the option(s) that displays text matching the argument.
deselectAll()
Deselects all options.
getAllSelectedOptions()
Returns a List<WebElement> of all selected options.
getFirstSelectedOption()
Returns a WebElement representing the first selected option.
getOptions()
Returns a List<WebElement> of all options.
isMultiple()
Returns true if this is a multi-select list; false otherwise.

You can simulate mouse-hover events and perform drag-and-drop operations using RenderedWebElement.
RenderedWebElement Methods
Method
Purpose
dragAndDropBy(int moveRightBy,
int moveDownBy)
Drags and drops the element moveRightBy pixels to the right and moveDownBy pixels down. Pass negative arguments to move left and up.
dragAndDropOn(RenderedWeb
Element element)
Drags and drops the element on the supplied element.
getLocation()
Returns a java.awt.Point representing the top left-hand corner of the element.
getSize()
Returns a java.awt.Dimension representing the width and height of the element.
getValueOfCssProperty(String
propertyName)
Returns the value of the provided property.
hover()
Simulates a mouse hover event over the element.
isDisplayed()
Returns true if the element is currently displayed; otherwise false.