Sunday, November 17, 2013

WebDriver Methods in Selenium

WebDriver Methods:

1.Get :
               Load a new web page in the current browser window.
               driver.get(url);

2.Get Current URL :
          Get a string representing the current URL that the browser is looking at.
          String url = driver. getCurrentUrl();

3.Get Title :
            The title of the current page.
           String url = driver. getTitle ();
4.FindElement :
                1.Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached.
                2.findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
                3.Returns The first matching element on the current page
                4.Throws NoSuchElementException - If no matching elements are found

                 WebElement element = driver.findElement(By.id(“”))

5.FindElements :
              1.Find all elements within the current page using the given mechanism. This method is affected by the 'implicit wait' times in force at the time of execution.
              2.When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
              3.Returns : A list of all WebElements, or an empty list if nothing matches
List<WebElement> elements = driver.findElements(By.id(""));

6.Close :
            Close the current window, quitting the browser if it's the last window currently open.
            driver.close();  //To be used when we want to close any window

7.Quit :
            Quits this driver, closing every associated window.
            driver.quit(); // To be used at the end of the script

8.getWindowHandles :
          1. Return a set of window handles which can be used to iterate over all open windows of this webdriver instance by passing them to driver.switchTo().window(String)
          2. Returns : A set of window handles which can be used to iterate over all open windows.

9.getWindowHandle :
              Return an opaque handle to this window that uniquely identifies it within his driver instance. This can be used to switch to this window at a later date
10.Navigate :
              An abstraction allowing the driver to access the browser's history and to navigate to a given URL.

11.switchTo :
           Send future commands to a different frame or window.

12. manage :
           Gets the Option interface


WebElement:
  driver.findElement(By.id("WebelemntId")).clear();
driver.findElement(By.id("WebelemntId")).isEnabled();
driver.findElement(By.id("WebelemntId")).isDisplayed();
driver.findElement(By.id("WebelemntId")).submit();
driver.findElement(By.id("WebelemntId")).sendKeys("test");
driver.findElement(By.id("WebelemntId")).isSelected();
driver.findElement(By.id("WebelemntId")).getAttribute("");
driver.findElement(By.id("WebelemntId")).getLocation();
driver.findElement(By.id("WebelemntId")).getTagName();
driver.findElement(By.id("WebelemntId")).getText();
driver.findElement(By.id("WebelemntId")).getSize();
WebDriver >> Manage
1.Maximize:
driver.manage().window().maximize();

2.Get Window Size:
org.openqa.selenium.Dimension maximizeDim;
maximizeDim=driver.manage().window().getSize();

WebDriver >> Navigate
1. Refresh:
Refresh the current page

driver.navigate().refresh();
2. Back :
Move back a single "item" in the browser's history.

driver.navigate().back();
3. Forward :
Move a single "item" forward in the browser's history. Does nothing if we are on the latest page viewed.

driver.navigate().forward();
4. To :
Load a new web page in the current browser window.

driver.navigate().to(driver.getCurrentUrl());

Explicit and Implicit Waits:
Implicit Waits:
1. An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
2. The default setting is 0.
3. Once set, the implicit wait is set for the life of the WebDriver object instance.
4. Will be set as soon driver object is created

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);


implicitlyWait :
1. Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
2. When searching for a single element, the driver should poll the page until the element has been found, or this timeout expires before throwing a NoSuchElementException. When searching for multiple elements, the driver should poll the page until at least one element has been found or this timeout has expired.
3. Increasing the implicit wait timeout should be used judiciously as it will have an adverse effect on test run time, especially when used with slower location strategies like XPath.
 pageLoadTimeout:
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

WebDriver : Java Script
JavascriptExecutor js=(JavascriptExecutor) driver;
1. String readyState=(String)js.executeScript("return document.readyState");
System.out.println("readyState  : "+readyState);
2. String title=(String)js.executeScript("return document.title");  System.out.println("title  : "+title);
         
3. String domain=(String)js.executeScript("return document.domain");  System.out.println("domain  : "+domain);
         
4. String lastModified=(String)js.executeScript("return document.lastModified");
System.out.println("lastModified  : "+lastModified);
5. String URL=(String)js.executeScript("return document.URL");   System.out.println("Full URL  : "+URL);

6. String error=(String) ((JavascriptExecutor) driver).executeScript("return window.jsErrors");  System.out.println("Windows js errors  :   "+error);

5 different ways to refresh a webpage using Selenium Webdriver
1. Using sendKeys.Keys method

driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);

2. Using navigate.refresh()  method

driver.get("https://accounts.google.com/SignUp");  
driver.navigate().refresh();

3. Using navigate.to() method

driver.get("https://accounts.google.com/SignUp");  
driver.navigate().to(driver.getCurrentUrl());

4. Using get() method

driver.get("https://accounts.google.com/SignUp");  
driver.get(driver.getCurrentUrl());

5. Using sendKeys() method

driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname- placeholder")).sendKeys("\uE035");


Getting total no.of dropdown menus on a Webpage :
Here is the sample code to get the total no.of dropdown menus on a facebook registration page:
driver.get("http://facebook.com");
List<webelement> dropdown=driver.findElements(By.tagName("select"));
System.out.println("total dropdown lists "+dropdown.size());

Getting total no.of textboxes on a Webpage :
Here is the sample code to get the total no.of textboxes on facebook registration page:
driver.get("http://facebook.com");
List <webelement> textboxes=driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
System.out.println("total textboxes "+textboxes.size());


Here is the sample code to get the total no.of textboxes on hotmail registration page:

driver.get("https://signup.live.com");
List <webelement> totalTextboxes=driver.findElements(By.xpath("//input[@type='text']"));
System.out.println("total textboxes "totalTextboxes.size());


Getting total no.of iframes on a Webpage :
Here is the sample code to get the total no.of iframes :

driver.get("https://www.facebook.com/googlechrome/app_158587972131");
List <webelement> totaliFrames=driver.findElements(By.tagName("iframe"));
System.out.println("total links "+totaliFrames.size());

Handling Security Certificates in Firefox using WebDriver
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("setAcceptUntrustedCertificates","true");
driver = new FirefoxDriver(profile);

Fire Event:
1. driver.switchTo().activeElement().sendKeys(Keys.TAB);

2. WebElement element = driver.findElement(By.id("myElement"));

JavascriptLibrary javascript = new JavascriptLibrary();

 javascript.callEmbeddedSelenium(driver, "triggerEvent", element, "blur");
Screen Shot:
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(scrFile, new File("c:\\careerbuilder.jpg"));

WebDriverWait:
1. // Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

2. WebDriverWait wait = new WebDriverWait(driver, 30);

 wait.pollingEvery(2, TimeUnit.SECONDS);

//1. Ignore Exceptions
// 2.  Can add any number of exceptions in the webdriver wait

 wait.ignoring(NoSuchElementException.class,  NoSuchFrameException.class);

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

Alerts:

Alert alert = driver.switchTo().alert();
       
1. String AlertText = alert.getText();        
2. alert.accept();
3. alert.dismiss();
4. alert.sendKeys("");
       if(isAlertPresent()){
            driver.switchTo().alert();
            driver.switchTo().alert().accept();
            driver.switchTo().defaultContent();
        }

public boolean isAlertPresent(){
        try{
            driver.switchTo().alert();
            return true;
        }//try
        catch(Exception e){
            return false;
        }//catch
    }

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...