Single Post

Header

Monday, November 23, 2015

How to fetch all links and click one of those links one by one using selenium webdriver

How to get all the links on a webpage and click the matching website

import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class LinksAllTypesMethods {

@Test
public void seleniumLinkMethods() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
Thread.sleep(3000);

// Using tag name "a" , we get all the links
List<WebElement> links = driver.findElements(By.tagName("a"));

// Get how many web links are present on a web page
int numberOfWebLinks = links.size();

// Get the text from the links
for (WebElement link : links) {
System.out.println("The link is "+link.getText());
}

// Using for loop
for (int i=0; i<numberOfWebLinks; i++) {
System.out.println(links.get(i).getText());
System.out.println(links.get(i).getAttribute("href"));
}

// Using tag name "a" , we get all the links
List<WebElement> allLinks = driver.findElements(By.tagName("a"));

// Click on a particular link and break it
   for(WebElement singleLink : allLinks) {
    if (singleLink.getText().equals("हिन्दी")) {
    singleLink.click();
    Thread.sleep(3000);
    break;
    }
   }

driver.close();
}
}


Output :
The link is
The link is Gmail
The link is Images
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is Sign in
The link is ×
The link is Yes, show me
The link is
The link is
The link is
The link is
The link is हिन्दी
The link is বাংলা
The link is తెలుగు
The link is मराठी
The link is தமிழ்
The link is ગુજરાતી
The link is ಕನ್ನಡ
The link is മലയാളം
The link is ਪੰਜਾਬੀ
The link is Privacy
The link is Terms
The link is Settings
The link is
The link is
The link is
The link is
The link is
The link is Advertising
The link is Business
The link is About

https://www.google.co.in/setprefs?suggon=2&prev=https://www.google.co.in/&sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D
Gmail
https://mail.google.com/mail/?tab=wm
Images
https://www.google.co.in/imghp?hl=en&tab=wi&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKouCBIoAQ

https://www.google.co.in/intl/en/options/

https://myaccount.google.com/?utm_source=OGB

https://www.google.co.in/webhp?tab=ww&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCAEoAQ

https://maps.google.co.in/maps?hl=en&tab=wl

https://www.youtube.com/?gl=IN

https://play.google.com/?hl=en&tab=w8

https://news.google.co.in/nwshp?hl=en&tab=wn&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCAUoBQ

https://mail.google.com/mail/?tab=wm

https://drive.google.com/?tab=wo

https://www.google.com/calendar?tab=wc

https://plus.google.com/?gpsrc=ogpy0&tab=wX

https://translate.google.co.in/?hl=en&tab=wT

https://photos.google.com/?tab=wq

https://www.google.co.in/intl/en/options/

https://docs.google.com/document/?usp=docs_alc

https://books.google.co.in/bkshp?hl=en&tab=wp&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCA0oDQ

https://www.blogger.com/?tab=wj

https://www.google.com/contacts/?hl=en&tab=wC

https://www.google.co.in/intl/en/options/
Sign in
https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.co.in/
×
javascript:void(0)
Yes, show me
https://www.google.com/url?q=https://www.google.com/homepage/hp-firefox.html%3Futm_source%3Dgoogle.com%26utm_medium%3Dcallout%26utm_campaign%3DFFDHP&source=hpp&id=5082229&ct=7&usg=AFQjCNGpJYJLVlrP4aS5wSlNy1fQs3_xmg

https://www.google.co.in/webhp?hl=en

https://support.google.com/websearch/answer/186645?hl=en-IN

https://www.google.co.in/search?site=&q=%27Tis+the+season!&oi=ddle&ct=holidays-2015-day-1-6575248619077632-hp&hl=en&sa=X&ved=0ahUKEwjoy72y4fHJAhXMC44KHVivBi4QNggD

javascript:void(0);
हिन्दी
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=hi&source=homepage
বাংলা
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=bn&source=homepage
తెలుగు
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=te&source=homepage
मराठी
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=mr&source=homepage
தமிழ்
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=ta&source=homepage
ગુજરાતી
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=gu&source=homepage
ಕನ್ನಡ
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=kn&source=homepage
മലയാളം
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=ml&source=homepage
ਪੰਜਾਬੀ
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=pa&source=homepage
Privacy
https://www.google.co.in/intl/en/policies/privacy/?fg=1
Terms
https://www.google.co.in/intl/en/policies/terms/?fg=1
Settings
https://www.google.co.in/preferences?hl=en

https://www.google.co.in/preferences?hl=en-IN&fg=1

https://www.google.co.in/advanced_search?hl=en-IN&fg=1

https://www.google.co.in/history/optout?hl=en-IN&fg=1

https://support.google.com/websearch/?p=ws_results_help&hl=en-IN&fg=1

javascript:void(0)
Advertising
https://www.google.co.in/intl/en/ads/?fg=1
Business
https://www.google.co.in/services/?fg=1
About
https://www.google.co.in/intl/en/about.html?fg=1


Double click in selenium webdriver


How to double click using Selenium WebDriver

import org.junit.Test;
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.interactions.Actions;


public class DoubleClickOnAnElement {

 @Test
 public void doubleClick() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("https://www.google.co.in/");
  Thread.sleep(3000);
  WebElement element = driver.findElement(By.name("btnI"));
  Actions action = new Actions(driver);
  action.moveToElement(element).doubleClick().perform();
  Thread.sleep(2000);
  driver.close();  
 }

}

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

When do we get "StaleElementReferenceException" while doing with Selenium Web Driver

package SeleniumPractise;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;

public class StaleElementReferenceException {

  @Test
  public void getStaleElementReferenceException() throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://docs.seleniumhq.org/");
    driver.manage().window().maximize();
    Thread.sleep(2000);
    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(WebElement link : links) {
      System.out.println(link.getText());
    }
 
    for(WebElement link : links) {
  // We get error here, after click on link and come back to the link web element which is not available
 //  Because the page is moved to the other page where the link web element is not there
      if(link.getText().equals("Who made Selenium"))   {
        link.click();
        Thread.sleep(2000);
      }
    }
 
    driver.close();
  }

 @Test
  public void fixStaleElementReferenceException() throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://docs.seleniumhq.org/");
    driver.manage().window().maximize();
    Thread.sleep(2000);
    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(WebElement link : links) {
      System.out.println(link.getText());
    }
 
    for(WebElement link : links) {
      if(link.getText().equals("Who made Selenium"))   {
        link.click();
        Thread.sleep(2000);
        break;
      }
    }
 
    driver.close();
  }


}


Error Logs for the first menthod above :

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 18 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'vindukuri1.blr.corp.<company>.com', ip: '172.30.104.73', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-71-generic', java.version: '1.8.0-google-v7'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=43.0, platform=LINUX, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: b2af66d3-35e0-47f0-8e85-c3d05417812b
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:178)
at SeleniumPractise.getLinksOnPage.getAllLinksOnAWebPage(getLinksOnPage.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'vindukuri1.blr.corp.google.com', ip: '172.30.104.73', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-71-generic', java.version: '1.8.0-google-v7'
Driver info: driver.version: unknown
at <anonymous class>.fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:9351)
at <anonymous class>.Utils.getElementAt(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:8978)
at <anonymous class>.WebElement.getElementText(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11965)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)

Friday, November 20, 2015

Browser navigation's using Selenium WebDriver

Selenium Webdriver Browser navigations:
1.Open url
2.Maximize browser
3.Click on a link
4.Back,Forward and Refresh browser
5.Close the browser

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

public class Browser_Navigations {

public static void main(String args[]) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://docs.seleniumhq.org/");
driver.manage().window().maximize();
driver.findElement(By.id("menu_documentation")).click();
Thread.sleep(2000);
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
driver.close();
}

}

Sunday, November 1, 2015

how to configure selenium webdriver in eclipse

Configure Selenium WebDriver with Eclipse

1.Download Selenium Libraries
http://seleniumhq.org/download/
Language Client Version  Release Date  (Java 2.25.0)   --> zip file
Extract the zip file and put all the jar files in one folder

2. Create a new Java Project in eclipse
File->New->Java Project (Enter any project name)  ->Finish


3. Add Selenium Libraries : In Eclipse
Expand the project (which we created) ->Right Click on (Java System Library) ->Build Path ->
Configure Build Path -> Add External Jars (Click) ->(Browse and Choose all jar files) ->ok

Simple Selenium WebDriver Example :

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

public class WebBrowser_Open_Get_Close {

    public static void main(String[] args) throws Exception
    {
        WebDriver ff = new FirefoxDriver();
        ff.get("http://www.google.co.in");
        Thread.sleep(3000);
        ff.findElement(By.name("q")).sendKeys("selenium");
        Thread.sleep(2000);
        //    WebElement we= ff.findElement(By.name("q"));
        ff.findElement(By.name("btnG")).click();
        System.out.println(ff.getTitle());
        Thread.sleep(3000);
        ff.close();
      
    }

}

How to get text from a textbox using Selenium WebDriver

Get text from textbox in Selenium WebDriver
we can use element.getAttribute("value")

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class getTextFromTextBox {

 @Test
 public void testGetText() throws InterruptedException {
  WebDriver driver =  new FirefoxDriver();
  driver.get("https://www.google.co.in");
  driver.manage().window().maximize();
  Thread.sleep(2000);
  driver.findElement(By.cssSelector(".gsfi")).sendKeys("selenium testing");
  driver.findElement(By.name("btnG")).click();
  Thread.sleep(3000);
  String searchKeyword = driver.findElement(By.cssSelector(".gsfi")).getAttribute("value");
  System.out.println("The searched keyword is "+ searchKeyword);
  driver.close();
 }

@Test
 public void testGetTextFromTextBox() throws InterruptedException {
   WebDriver driver = new FirefoxDriver();
   driver.get("https://in.yahoo.com/");
   driver.manage().window().maximize();
   Thread.sleep(2000);
   driver.findElement(By.id("UHSearchBox")).sendKeys("selenium is automation test suite");
   driver.findElement(By.id("UHSearchWeb")).click();
   Thread.sleep(2000);
   String  textValue = driver.findElement(By.id("yschsp")).getAttribute("value");
   System.out.println("The searched keyword is "+ textValue);
   driver.close();
 }

}


Output :
The searched keyword is selenium is automation test suite
The searched keyword is selenium testing

How to get to know whether drop down list values are in sorted order or not - Selenium WebDriver

Drop down list values are in sorted order or not in Selenium WebDriver

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DropDownListSortedOrNot {

@Test
public void dropDownListSortedOrNot() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ebay.in/");
Thread.sleep(3000);
WebElement element = driver.findElement(By.id("gh-cat"));
element.click();
List<WebElement> dropDownvalues = element.findElements(By.tagName("option"));
ArrayList<String> listValues = new ArrayList<String>();
for(WebElement value : dropDownvalues) {
System.out.println("values are"+ value.getText());
listValues.add(value.getText());
}
boolean sortedOrNot = sortedOrNot(listValues);
assertEquals(true, sortedOrNot);
driver.close();

}

public boolean sortedOrNot(ArrayList<String> dropDownValues) {
System.out.println("number of values "+ dropDownValues.size());
for(int i=0; i<dropDownValues.size();i++) {
int temp = dropDownValues.get(i).compareTo(dropDownValues.get(i+1));
if(temp>1) {
System.out.println("i value"+i);
return false;
}
}
return true;
}


}

How to display the dropdown list values in Selenium WebDriver

Display the values fromm the dropdown list using Selenium WebDriver:
1.Creare WebElement variable pointing the dropdown list
2.Get List object using above webelement
3.Display them using for through for each loop

import java.util.List;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumForEach {

@Test
public void dropDownList() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
Thread.sleep(4000);
// Get the Drop Down element and create an object for that.
WebElement button = driver.findElement(By.cssSelector(".flight_status"));
button.click();
Thread.sleep(4000);
// Switch to the framework
driver.switchTo().frame("RSIFramestatus");
WebElement element = driver.findElement(By.name("originStation"));
   List<WebElement> values = element.findElements(By.tagName("Option"));
for(WebElement value:values) {
    System.out.println("city : "+value.getText());
   }
        driver.close();

}
}

Output:
city : Origin airport
city : Agartala (IXA)
city : Ahmedabad (AMD)
city : Amritsar (ATQ)
city : Aurangabad (IXU)
city : Bagdogra (IXB)
city : Belgaum (IXG)
city : Bengaluru (BLR)
city : Chandigarh (IXC)
city : Chennai (MAA)
city : Coimbatore (CJB)
city : Colombo (CMB)
city : Dehradun (DED)
city : Delhi (DEL)
city : Dharamshala (DHM)
city : Dubai (DXB)
city : Goa (GOI)
city : Guangzhou (CAN)
city : Guwahati (GAU)
city : Hubli (HBX)
city : Hyderabad (HYD)
city : Indore (IDR)
city : Jabalpur (JLR)
city : Jaipur (JAI)
city : Jammu (IXJ)
city : Kabul (KBL)
city : Kathmandu (KTM)
city : Khajuraho (HJR)
city : Kochi (COK)
city : Kolkata (CCU)
city : Kozhikode (CCJ)
city : Lucknow (LKO)
city : Madurai (IXM)
city : Male (MLE)
city : Mandalay (MDL)
city : Mangalore (IXE)
city : Mumbai (BOM)
city : Muscat (MCT)
city : Mysore (MYQ)
city : Port Blair (IXZ)
city : Pune (PNQ)
city : Rajahmundry (RJA)
city : Sharjah (SHJ)
city : Srinagar (SXR)
city : Surat (STV)
city : Thiruvananthapuram (TRV)
city : Tirupati (TIR)
city : Tuticorin (TCR)
city : Udaipur (UDR)
city : Varanasi (VNS)
city : Vijayawada (VGA)
city : Vishakhapatnam (VTZ)

How to get List Elements and Select a Value from a DropDown List - Selenium WebDriver

How to Select a value from a DropDown List using Selenium - WebDriver

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.Select;
public class MySpiceJet {

   
    public static void main(String[] args) throws Exception
    {
        WebDriver wd=new FirefoxDriver();
        wd.get("http://www.spicejet.com/");
        Thread.sleep(10000);
       
        WebElement from1=wd.findElement(By.id("from1Select"));
        // Get the list from the drop down list Selenium WebDriver
        List<WebElement> list1=from1.findElements(By.tagName("option"));
        for(WebElement i:list1)
        {
            System.out.println(i.getText());
            //Reporter.log(i.getText());
        }
            // Select a value from the drop down list Selenium WebDriver
            Select select=new Select(wd.findElement(By.id("from1Select")));
            select.selectByVisibleText("Tirupati");  

        wd.close();
    }

}

How to handle right click in Selenium WebDriver

Handling right click using Selenium WebDriver
Steps to handle this:
1.Open web browser
2.Get webelement for the object
3.Create an object for Driver
4.From Action object, create context click on to perform Right click on the object
5.Use sendKeys to point arrow to right top line menu, and then move Down/Click

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class SeleniumRhtClickAndWindowsHandles {

@Test
public void rightClickHandles() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://docs.seleniumhq.org/");
Thread.sleep(3000);
WebElement element = driver.findElement(By.cssSelector("#menu_documentation a"));
Actions action = new Actions(driver); //Create an action object for driver
  action.contextClick(element).build().perform();  // Right click
action.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(2000);
action.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(2000);
action.sendKeys(Keys.ENTER).build().perform();
Thread.sleep(2000);
driver.close();
}
}

Select value from dropdown list in selenium

Select a value from DropDown list using Selenium

Steps to select a value from through selenium
1.Open the website
2.Create an object for the dropdown list
3.Convert the above object into Select object
4.Select a value By Index/Value/Text

package SeleniumPractise;


import java.util.List;
import org.junit.Test;
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 DisplayDropDownListValues {

 @Test
 public void displayDropDownList() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.spicejet.com/");
  driver.manage().window().maximize();
  Thread.sleep(4000);
  // Get the Drop Down element and create an object for that.
  WebElement button = driver.findElement(By.cssSelector(".flight_status"));
  button.click();
  Thread.sleep(4000);
  // Switch to the framework
  driver.switchTo().frame("RSIFramestatus");
  WebElement element = driver.findElement(By.name("originStation"));
     List<WebElement> values = element.findElements(By.tagName("Option"));
  for(WebElement value:values) {
      System.out.println("city : "+value.getText());
     }
        driver.close();

 }
 @Test
 public void dropDownListDenstinationValues() throws InterruptedException {
   WebDriver driver = new FirefoxDriver();
   driver.get("http://www.spicejet.com/");
   driver.manage().window().maximize();
   Thread.sleep(2000);
   WebElement button = driver.findElement(By.cssSelector(".flight_status a"));
   button.click();
   Thread.sleep(3000);
   driver.switchTo().frame("RSIFramestatus");
   WebElement element = driver.findElement(By.name("originStation"));
   Select selectObject = new Select(element);
   selectObject.selectByVisibleText("Bengaluru (BLR)");
   System.out.println("The selected value is"+selectObject.getFirstSelectedOption().getText());
   Thread.sleep(3000);
   WebElement destination = driver.findElement(By.name("destinationStation"));
   Select selectDestination = new Select(destination);
   selectDestination.selectByValue("DEL");
   Thread.sleep(2000);
   driver.close();
 }

 @Test
 public void selectValueFromdropDownList() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.spicejet.com/");
  driver.manage().window().maximize();
  Thread.sleep(3000);

  // Get the Drop Down list element and create an object for that.
  // <select id="ctl00_mainContent_ddl_Child">
  WebElement element = driver.findElement(By.id("ctl00_mainContent_ddl_Child"));
  // Convert the element into Select object
  Select selectObject = new Select(element);
  selectObject.selectByIndex(2);     //Select by Index                              
  Thread.sleep(3000);
 // <option value="3">3 Children</option>
  selectObject.selectByValue("3");     //Select by Value                          
  Thread.sleep(3000);
 // <option value="1">1 Child</option>
  selectObject.selectByVisibleText("1 Child");   //Select by Visible text
Thread.sleep(3000);
  // To print the above selected value in console window
  System.out.println("The selected value is"+selectObject.getFirstSelectedOption().getText());
  driver.close();

 }
}


AssertTrue and AssertEquals in Selenium WebDriver

Examples for AssertTrue and AssertEquals using Selenium WebDriver

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import org.apache.commons.io.FileUtils;

public class AssertTrueAssertEquals {
   
    @Test
    public void asserttrue() throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in");
        driver.manage().window().maximize();
        Thread.sleep(2000);
        driver.findElement(By.
className("gsfi")).sendKeys("testing");
        driver.findElement(By.name("btnG")).click();
        Thread.sleep(3000);
        WebElement resultsLabel = driver.findElement(By.id("resultStats"));
        assertTrue(resultsLabel.isDisplayed());

        driver.close();
    }
   
    @Test
    public void assertequals() throws InterruptedException, IOException {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in");
        driver.manage().window().maximize();
        Thread.sleep(2000);
        driver.findElement(By.
className("gsfi")).sendKeys("abcdefghijkl1234324254");
        driver.findElement(By.name("btnG")).click();
        Thread.sleep(3000);
        // take the screenshot
        File scrFile = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        // now save the screenshot to a file some place
        FileUtils.copyFile(scrFile, new File("e:\\tmp\\screenshot.png"));
        WebElement resultsLabel = driver.findElement(By.id("resultStats"));
        assertEquals(true, resultsLabel.isDisplayed());

        driver.close(); // This will not execute if the above assert fails otherwise it will execute.
    }
   
}

How to handle multiple windows in Selenium WebDriver and switch to the required window

import java.util.Set;

package SeleniumPractise;

import java.util.Set;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class ActionsAndWindows {

 @Test
 public void newWindows() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://docs.seleniumhq.org/");
  driver.manage().window().maximize();
  System.out.println(driver.getTitle());
  System.out.println(driver.getCurrentUrl());
  Thread.sleep(3000);
  WebElement element1 = driver.findElement(By.cssSelector("#menu_documentation a"));
  Actions action1 = new Actions(driver);
  action1.contextClick(element1).build().perform();
  action1.sendKeys(Keys.ARROW_DOWN).build().perform();
  action1.sendKeys(Keys.ARROW_DOWN).build().perform();
  Thread.sleep(2000);
  action1.sendKeys(Keys.ENTER).build().perform();
  Thread.sleep(2000);
  WebElement element2 = driver.findElement(By.cssSelector("#menu_projects a"));
  Actions action2 = new Actions(driver);
  action2.contextClick(element2).build().perform();
  action2.sendKeys(Keys.ARROW_DOWN).build().perform();
  action2.sendKeys(Keys.ARROW_DOWN).build().perform();
  Thread.sleep(2000);
  action2.sendKeys(Keys.ENTER).build().perform();
  Thread.sleep(2000);
  WebElement element3 = driver.findElement(By.cssSelector("#menu_support a"));
  Actions action3 = new Actions(driver);
  action3.contextClick(element3).build().perform();
  action3.sendKeys(Keys.ARROW_DOWN).build().perform();
  action3.sendKeys(Keys.ARROW_DOWN).build().perform();
  Thread.sleep(2000);
  action3.sendKeys(Keys.ENTER).build().perform();
  Thread.sleep(2000);
  Set<String> windows = driver.getWindowHandles();
  System.out.println("Number of windows " + windows.size());
  String neededWindow = "Selenium Projects";
  for (String window : windows) {
   WebDriver requiredWindow = driver.switchTo().window(window);
   System.out.println(requiredWindow.getTitle());
   if (requiredWindow.getTitle().equals(neededWindow)) {
    System.out.println(requiredWindow.getTitle());
    break;
   }
  }
  driver.findElement(By.linkText("Selenium WebDriver")).click();
  Thread.sleep(3000);

   driver.close(); // Closes the current browser

   Thread.sleep(3000);
  driver.quit();
 }
}


Output:
Selenium - Web Browser Automation
http://docs.seleniumhq.org/
Number of windows 4
Selenium - Web Browser Automation
Selenium Documentation — Selenium Documentation
Selenium Projects
Selenium Projects

How to handle Actions using Selenium WebDriver

Handle Actions using Selenium WebDriver

package SeleniumPractise;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class ActionsHandle {
  
  @Test
  public void handleActions() throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://docs.seleniumhq.org/");
    Thread.sleep(2000);
    WebElement element = driver.findElement(By.cssSelector("#menu_documentation a"));
    Actions act = new Actions(driver);
    // Right click on the web element
    act.contextClick(element).build().perform();
    Thread.sleep(2000);
    // Arrow down
    act.sendKeys(Keys.ARROW_DOWN).build().perform();
    Thread.sleep(2000);
    // Click on it
    act.sendKeys(Keys.ENTER).build().perform();
    Thread.sleep(2000);
    WebElement support = driver.findElement(By.cssSelector("#menu_support a"));
    // Double Click on an element
    act.moveToElement(support).doubleClick().perform();
    Thread.sleep(2000);
    driver.close();
  }

}

How to count the number of options in a select dropdown box in selenium

Count the number of elements in a dropdown list using Selenium

Steps:
1.Open web browser
2.Get the element of the dropdown list
3.Get the list elements using above webelement
4.Get the size of the list using size() method

import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CountNumberOfValues {
 @Test
 public void numberOfElementsDropDown() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.monsterindia.com/");
  Thread.sleep(4000);
  String parentWindow = driver.getWindowHandle();
  Set<String> windows = driver.getWindowHandles();
  for(String window : windows) {
    if(!parentWindow.equals(window)) {
      driver.switchTo().window(window);
      driver.close();
    }
  }
  driver.switchTo().window(parentWindow);
  Thread.sleep(3000);
  driver.findElement(By.id("selExp_id")).click();
  WebElement element = driver.findElement(By.cssSelector(".single_select"));
  List<WebElement> elements = element.findElements(By.cssSelector(".option_item"));
  int numberOfValues = elements.size();
  System.out.println("The number of elements in the dropdown list "+numberOfValues);
  driver.quit();
 }

}

Ouput:
The number of elements in the dropdown list 52

How to handle Alerts using Selenium WebDriver

Selenium WebDriver - Alerts

package SeleniumPractise;

import static org.junit.Assert.*;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AlertsHandle {
 
    @Test
    public void alertsHandle() throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://ksrtc.in/");
        Thread.sleep(2000);
        driver.findElement(By.cssSelector(".button1.redbtn")).click();
        Thread.sleep(2000);
        Alert alt = driver.switchTo().alert();
        String exp_msg = alt.getText(); 
        System.out.println(exp_msg); 
        alt.accept();
        Thread.sleep(2000);
        assertEquals(exp_msg, "'From' place is required.");
        driver.quit();
    }
}

JUnit TestSuite Example in Selenium Java

Examples with JUnit TestSuite in Selenium

To execute particular classes as a test suite

@RunWith(Suite.class)
@SuiteClasses ({
FirstClass.class,
SecondClass.class
})

@Rule  
ErrorCollector  -- It is built in class in Junit used to collect errors and make the testcase fail if we use assertions.

1.MyJunitTestSuite.java

package junit;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses ({
FirstClass.class,
SecondClass.class
})
public class MyJunitTestSuite {


2. FirstClass.java
package junit;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class FirstClass {
@BeforeClass
public static void testBeforeClass() {
System.out.println("Before Class");
}
@AfterClass
public static void testAfterClass() {
System.out.println("After Class");
}
@Before
public void testBeforeMethod() {
System.out.println("Before Method");
}
@After
public void testAfterMethod() {
System.out.println("After Method");
}
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
}

3. SecondClass.java
package junit;

import org.junit.Ignore;
import org.junit.Test;

public class SecondClass {
@Test
public void test1() {
System.out.println("SecondClass - test1");
}
@Ignore
@Test
public void test2() {
System.out.println("Ignore method");
}
@Test
public void test3() {
System.out.println("SecondClass - test3");
}
}

Execute MyJunitTestSuite.java file

Output:
Before Class
Before Method
test1
After Method
Before Method
test2
After Method
After Class
SecondClass - test1
SecondClass - test3


JUnit annotations in Selenium WebDriver

Different JUnit annotations using Selenium WebDriver

@Test        --- Each test method
@Ignore      --- Ignore test
@Before      --- Before each test method inside a class
@After       --- After each test method inside a class
@BeforeClass --- Before class tests
@AfterClass  --- After class tests

package javaPrograms;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class JUnitAnnotations {
 
    private WebDriver driver;
 
    @BeforeClass
    public static void beforeClass() {
        System.out.println("This will execute before the class execution");
    }
 
    @Before
    public void setUp() {
        driver = new FirefoxDriver();
        driver.get("https://www.google.co.in/");
        System.out.println("Before method would execute before of ->Test methods");
    }
 
    @Before       // Generally we do not write multiple Before methods,but can write
    public void setUpDummy() {
        System.out.println("Before method would execute before of ->Test methods");
    }
 
    @Test
    public void testGoogleSearch() throws InterruptedException {
        driver.findElement(By.className("gsfi")).sendKeys("testing");
        driver.findElement(By.name("btnG")).click();
        System.out.println("Test methods would execute after ->Before methods");
        Thread.sleep(3000);
    }
 
    @After
    public void tearDown() {
        driver.close();
        System.out.println("After method would execute after ->Test methods");    
    }
 
    @AfterClass
    public static void afterClass() {
        System.out.println("This will execute after the class execution");
    }
}



Output:
This will execute before the class execution
Before method would execute before of ->Test methods
Before method would execute before of ->Test methods
Test methods would execute after ->Before methods
After method would execute after ->Test methods
This will execute after the class execution



TestNG simple example for Selenium - with Annotations

Selenium simple example for TestNG with different Annotations


import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class testng_example1 {


    @BeforeSuite
    public void BeforeSuite()
    {
        System.out.println("BeforeSuite will  be executed before the entire test");
    }
   
    @AfterSuite
    public void AfterSuite()
    {
        System.out.println("AfterSuite will  be executed after the entire test");
    }
   
        @Test
        public void testmehtod1()
        {
            System.out.println("welcome to testng method1");
        }
       
        @Test
        public void testmehtod2()
        {
            System.out.println("welcome to testng method2");
        }
       
        @BeforeTest
        public void BeforeTest()
        {
            System.out.println("BeforeTest will be executed before the testcases of that class ");
        }
       
        @AfterTest
        public void AfterTest()
        {
            System.out.println("AfterTest will be executed after the testcases of that class ");
        }
       
}

Output :

BeforeSuite will  be executed before the entire test
BeforeTest will be executed before the testcases of that class
welcome to testng method1
welcome to testng method2
AfterTest will be executed after the testcases of that class
PASSED: testmehtod1
PASSED: testmehtod2

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

AfterSuite will  be executed after the entire test

Configure TestNG with Eclipse for Selenium


how to configure TestNG in eclipse

1.Configuration of TestNG with Eclipse for Selenium
Goto Eclipse ->Help ->Install New Software ->in "Work with" (give the url as
"http://beust.com/eclipse")->Select TestNG (check box)->Next->Next->Finish

2.
To check whether the TestNG is installed or not
Goto File->New->Other-> (TestNG would be present in the list)


The below steps are not required

Download testng jar file
testng.org/doc/download.htm

http://reportng.uncommons.org/

Include these jar files .
Rht Click on Referenced Libraries ->Build Path ->Add External Jars ->
Browse those two jar files

To create xml file
Rht click on Project ->New -> File -> (give any file name (ex:testng.xml)




Get values from the table using Selenium WebDriver

Get values from the table using Selenium WebDriver -
Print particular row of column value

import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class getValuesFromTable {

@Test
public void webdriverReadTable() throws InterruptedException {

WebDriver driver = new FirefoxDriver();
driver.get("http://content.icicidirect.com/newsiteContent/Market/MarketStats.asp?stats=DailySharePrices");
Thread.sleep(5000);
WebElement elementTable = driver.findElement(By.id("gridSource"));
List<WebElement> rows = elementTable.findElements(By.tagName("tr"));
int rowNumber = 0;
for(WebElement row : rows) {
rowNumber++;
List<WebElement> cols = row.findElements(By.tagName("td"));
int colNumber = 0;
for(WebElement col : cols) {
colNumber++;
if(rowNumber==4 && colNumber == 6) {
System.out.println("The 3rd row of 5th column element is: "+ col.getText());
}
// System.out.println("Each col is "+col.getText());
}
}
System.out.println(rows.get(2).getText());
driver.close();
}

}

Output:
The 3rd row of 5th column element is: 5791
Aadi Indus 4.22 4.22 4.22 4.22 2 1 4.00


How to execute Selenium WebDriver scripts in IE browser,Firefox browser and Chrome browser

Execute Selenium WebDriver scripts in IE browser,Firefox browser and Chrome browser

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;


public class IEFirefoxChromeBrowsers {

/*
 Open IE , Go to Tools -> Internet Options -> Security
Set all zones to the same protected mode, enabled or disabled should not matter.
Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.
*/

@Test
public void ieBrowser() throws InterruptedException {
  System.setProperty("webdriver.ie.driver", "E:\\Selenium\\IEDriverServer\\IEDriverServer.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.get("http://docs.seleniumhq.org/");
  Thread.sleep(3000);
  driver.close();
}

// No settings required for firefox execution.
@Test
public void fireFoxBrowser() throws InterruptedException {
 WebDriver driver = new FirefoxDriver();
 driver.get("http://www.google.co.in");
 Thread.sleep(3000);
 driver.close();
}

// Download chromedriver.exe and write the code like below.
@Test
public void chromeBrowser() throws InterruptedException {
  System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("http://docs.seleniumhq.org/");
  Thread.sleep(3000);
  driver.close();
}

}

Selenium WebDriver - Absolute and Relative Path Examples

Example Absolute and Relative Paths for Selenium WebDriver

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class AbsoluteRelativePaths {

@Test
public void absolutePath() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("E:\\Selenium\\absolute.html");

  // Absolute Path starts from root path
  WebElement link1 = driver.findElement(By.xpath("/html/body/li[@id='test']/a"));

  // Relative Path starts from current path
  WebElement link2 = driver.findElement(By.xpath(".//*[@id='test']/a"));

  driver.quit();

}

}

File Upload using Selenium WebDriver and Auto it scripts

File Upload using Selenium WebDriver and Auto it scripts

import java.io.IOException;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {

@Test
public void fileUpLoad() throws InterruptedException, IOException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.sendspace.com/");
Thread.sleep(3000);
driver.findElement(By.id("upload_file")).click();
Runtime.getRuntime().exec("E:\\Selenium\\fileUpload.exe"); 
driver.close();
}

}

Auto it script : File name given as - fileUpload.au3.  
Right click on the file and click on compile script. Generates fileUpload.exe file

WinWaitActive("File Upload")
Send("E:\Selenium\testFile.txt")
ControlClick("", "&Open", "Button1")

How to execute Selenium WebDriver in Chrome Browser

Run scripts in Chrome browser using Selenium WebDriver

1. Download chromedriver.exe file
2. Set the system property by the path
3. Use ChromeDriver


import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class ChromeBrowserTest {
@Test
public void chromeBrowser() throws InterruptedException {

  System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver_win32\\chromedriver.exe");
  
    // On ubuntu
   // System.setProperty("webdriver.chrome.driver", "/usr/local/google/home/vindukuri/Desktop/testing1/chromedriver");

   WebDriver driver = new ChromeDriver();

  driver.get("http://docs.seleniumhq.org/");
  Thread.sleep(3000);
  driver.close();
}
}

How to take screen shot in Selenium WebDriver

Take screen shot using Selenium WebDriver

package SeleniumPractise;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TakeScreenShot {
 
    @Test
    public void takeScreenShot() throws InterruptedException, IOException  {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in");
        driver.manage().window().maximize();
        Thread.sleep(2000);
        driver.findElement(By.className("gsfi")).sendKeys("abcdefghijkl1234324254");
        driver.findElement(By.name("btnG")).click();
        Thread.sleep(3000);

        // take the screenshot
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // now save the screenshot to a file at some place
        // FileUtils.copyFile(srcFile, new File("e:\\tmp\\screenshot.png")); // On windows

        FileUtils.copyFile(srcFile, new File("/usr/local/google/home/venkat/Desktop/testing1/s.png")); // On Ubuntu
         
        WebElement resultsLabel = driver.findElement(By.id("resultStats"));
        assertEquals(true, resultsLabel.isDisplayed());
        driver.close(); // This will not execute if the above statement fails.
    }

}

How to handle iFrames in Selenium WebDriver

Handling iFrames using Selenium WebDriver :
Steps to Follow:
1.Open web application
2.Switch driver to that Frame
3.Perform further steps
package SeleniumPractise;

import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SwitchToiFrame {

 @Test
 public void switchToiFrame() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.spicejet.com/");
  driver.manage().window().maximize();
  Thread.sleep(4000);
  // Get the Drop Down element and create an object for that.
  WebElement button = driver.findElement(By.cssSelector(".flight_status"));
  button.click();
  Thread.sleep(4000);
  // Switch to iFrame
 //<iframe id="RSIFramestatus" src="http://book.spicejet.com/CompactFlightStatus.aspx" >
  driver.switchTo().frame("RSIFramestatus");
  WebElement element = driver.findElement(By.name("originStation"));
     List<WebElement> values = element.findElements(By.tagName("Option"));
  for(WebElement value:values) {
      System.out.println("city : "+value.getText());
     }
        driver.close();

 }
}

Selenium WebDriver Examples for different locator methods of "By" class

Example for how to locate Selenium WebDriver methods of By class 
Explained with examples of all the methods of Selenium web driver By class

1.By.id 
2.By.name
3.By.className
4.By.linkText
5.By.partialLinkText
6.By.cssSelector
7.By.xpath
8. By.tagName

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumDifferentLocators {

@Test
public void seleniumByMethods() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
// Open website
driver.get("http://docs.seleniumhq.org/");
// Maximize web browser
driver.manage().window().maximize();

// Use By.name Webdriver
// Send "selenium" text at search selenium textbox.
// <input id="q" type="text" size="30" accesskey="s" name="q">
driver.findElement(By.name("q")).sendKeys("selenium");

// Use By.id Webdriver
// Click on "Go" button besides at search selenium textbox.
// <input id="submit" type="submit" value="Go">
driver.findElement(By.id("submit")).click();
Thread.sleep(3000);
// Navigate browser to back
driver.navigate().back();
Thread.sleep(3000);

// Use By.className Webdriver
// Click on "Download Selenium"
// <div class="downloadBox">
   driver.findElement(By.className("downloadBox")).click();

// Use By.linkText Webdriver
// Click on "Documentation" tab
 // <a title="Technical references and guides" href="/docs/">Documentation</a>
driver.findElement(By.linkText("Documentation")).click();
Thread.sleep(3000);

// Use By.partialLinkText Webdriver. Giving partial text of the link.
/* <a class="reference internal" href="01_introducing_selenium.jsp#test-automation-for-web-applications"> Test Automation for Web Applications</a> */
driver.findElement(By.partialLinkText("Test")).click();
driver.navigate().back();
Thread.sleep(3000);

// Use By.cssSelector Webdriver
// Click on "Download Selenium"
// <a class="reference internal" href="00_Note_to-the-reader.jsp">
   driver.findElements(By.cssSelector(".reference.internal")).get(0).click();
driver.navigate().back();
Thread.sleep(3000);

// Use By.xpath Webdriver
// Click on "About" tab
// <li id="menu_about"> <a title="Overview of Selenium" href="/about/">About</a> </li>
driver.findElement(By.xpath(".//*[@id='menu_about']/a")).click();

  // Use By.tagName Webdriver
  // Get "Browser Automation" text
  // <a title="Return to Selenium home page" href="/">Browser Automation</a>
  String linkName = driver.findElement(By.tagName("a")).getText();
  System.out.println(linkName);

// Close the browser
driver.close();
}


}