Showing posts with label Selenium Tutorials. Show all posts
Showing posts with label Selenium Tutorials. Show all posts

Selenium Xpath Tutorial Step by Step Guide

Selenium Xpath Tutorial Step by Step Guide provides real time examples to identify the elements with xpath in selenium Automation Testing,we can use xpath in Selenium Automation Testing when elements are not identify by the default locators,in this tutorial you will learn how to write xpath for different elements in a webpages for Selenium Automation Testing.

Selenium Xpath Tutorial Step by Step Guide

Selenium XPath Tutorial


Selenium Xpath Tutorial Step by Step Guide

Selenium Xpath Tutorial useful in identifying the elements in a webpage if default elements attributes are not provided by the application or in HTML pages.Let's start Xpath in Selenium,how to write xpath in selenium for web elements with examples.While you can identify the selenium xpath using some tools ,those are

Also Read:


Firebug - Firefox Plugin to identify element and to get xpath for elements with the help of Fire-path
WebDriver Element Locator tool - By this tool you can find xpath in C# , JAVA , PYTHON AND RUBY languages and separate X PATH locators also.You can download
this tool from Here(WebDriver Element Locator).

Selenium xpath can written in two ways.those are as follows


1.Absolute Path – Locating the Elements from root element to destination elements through the nodes and attributes.
2.Relative Path – In Relative path, xpath can be write with the help of
  1. Tag names
  2. Attribute names
  3. Attribute values

Relative Path:

Xpath in Selenium can be written in Relative path as based on tag names,tag attributes name and tag attributes values,let's see the below examples.

Syntax : //tagname[@attribute name='attribute value']


Relative Path Examples:

If we have taken input type tagname for below code

Xpath for Input Tag with attributes : 

<input id="firstname" name="firstname"/>
You can write xpath for above code as below

Tag name - input
Attribute name - id, name
Attribute value - firstname

//input[@id='firstname']  
//input[@name='lastname']  

Example 2 : 

<input id="searchbox" class="gsfi" type="text" label="Search" title="Searchbox" name="wordsearch" />

For above code you can write Selenium xpath as follows

XPATH:

//input[@id='searchbox']
//input[@class='gsfi']
//input[@type='text']
//input[@title='searchbox']
//input[@name='wordsearch']

Xpath using Contains keyword:

We can write Xpath in Selenium using element attributes but here i am using contains keyword,let's see below examples

<input id="searchbox" class="gsfi" type="text" label="Search" title="Searchbox" name="wordsearch" />

Xpath Examples:

//input[contains(@id,'searchbox')]
//input[contains(@class,'gsfi')]
//input[contains(@type,'text')]
//input[contains(@title,'searchbox')]
//input[contains(@name,'wordsearch')]

Xpath for href url link:

For example i am using below simple url link ,please see below xpath and html code.

<a class="gb_P" data-ved="0EMIuCBMoAA" href="https://mail.google.com/mail/?tab=wm" data-pid="23">Gmail</a>

You can write xpath for above code as below

tagname - a
tag attributes - class,data-ved,href
attribute values - gb_P,0EMIuCBMoAA,https://mail.google.com/mail/?tab=wm

XPATH:

//a[@data-ved='0EMIuCBMoAA']
//a[@class='gb_P']
//a[@href='https://mail.google.com/mail/?tab=wm']
//a[contains(@data-pid,'23')]
//a[contains(@data-ved,'0EMIuCBMoAA')]
//a[contains(@class,'gb_P')]
//a[contains(@href,'https://mail.google.com/mail/?tab=wm')]
//a[contains(@data-pid,'23')]


Xpath using and :

As we see till now you can write xpath with single attributes but now we can write with multiple attributes,let's see below example.

<input id="searchbox" class="gsfi" type="text" label="Search" title="Searchbox" name="wordsearch" />


XPATH:

//input[contains(@id, 'seaarchbox') and contains(@label,'seaarch')]
//input[contains(@class, 'gsf1') and contains(@label,'seaarch')]


Xpath for Dropdowns:

You can write different Xpath in Selenium for list boxes in order to select the list items,let's see below HTML code and xpath examples.

<select id="ArchiveMenu">
<option value="1">Banana</option>
<option value="2">Apple</option>
<option value="3">Selenium</option>
<option value="4">Automation Testing</option>
</select>


XPATH:

//select[@id='ArchiveMenu']
//select[contains(@id,'ArchiveMenu')]
//select[@value='1']
//select[contains(@value,'2')]
//select[contains(.,'Automation Testing')]
//select[contains(.,'Apple')]


2.Absolute path:

Absolute path uses complete path from the Root Element to the desire respective element.

Root Element - <html>
Desired Element - <div>,<input> etc

Example: /html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

Now let's how to write Absolute Xpath with below examples

HTML Code:

<html>
<head>
<title>Selenium Automation</title>
</head>
<body>
<form>
First Name:
<input type="text" name="firstname"><br>
Last Name:
<input type="text" name="lastname"><br>
Password:
<input type="password" name="pwd"><br>
Radio Button: Are you male or female?<br>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female<br>
Check Box: Check the languages you know<br>
<input type="checkbox" name="language" value="html">HTML<br>
<input type="checkbox" name="language" value="php">PHP<br>
<input type="checkbox" name="language" value="c">C<br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>

If i want to find First Name by xpath ,you can write as below

/html/body/form/input - FirstName
/html/body/form/input[2] - Lastname
/html/body/form/input[3] - Password
/html/body/form/input[4] - Male radio button

More Examples:

As you see above image i want to find the input search box element which is located under 3rd div - 1st div - input ,let's see the below xpath.
Selenium Xpath Tutorial guide
ABSOLUTE XPATH - EXAMPLE

XPATH:

/html/body/div/div[3]/form/div[2]/div[2]/div[1]/div[1]/div[3]/div/div/div[3]/div/input[1]

Root Element - /html/
Element Path - /body/div/div[3]/ before form
Path to Desire Element - Below Form -form/div[2]/div[2]/div[1]/div[1]/div[3]/div/div/div[3]/div/input[1]

Under form 2nd div
Under 2nd div - 2nd div
Under 2nd div - first div
Under first div - again first div
Under First div - again first div
Under First div - Thrid div div[3]

Like this path will continue for absolute path xpath in Selenium.

Count number of links in a webpage using Selenium

In this topic you will learn Count number of links in a webpage using Selenium which includes list , java.util.list.I have used java.awt.list in List then i am receiving this error message as RemoteWebElement cannot be cast to java.awt.List ,unable to find the solution every one is saying use list to find the size of the links for declared objects,But not able to find the solution at last find the solution as java.util.list i.e you need to use import java.util.list instead of import java.awt.list then only you can write the script as below.

Count number of links in a webpage using Selenium

In this we will use below simple code to count the links with the help of tagname as below.

List lists = (List) driver.findElements(By.tagName("a"));

Here By.tagName i am using why because all links in a webpages are identifying with tag that is the reason i'm using By.tagName("a");

Let's see the following example script to Count number of links in a webpage,by this example you will count links for any website.


package com.Payback.Actionconfig;

import java.util.List;

 import java.io.File;

 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.chrome.ChromeDriver;
 import org.openqa.selenium.chrome.ChromeOptions;
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.Test;


public class Practise {

public static WebDriver driver;
 String baseUrl;

@BeforeTest
 public void setup(){
 File Chromedriver = new File("F:\\Java_Applications\\Zip Files\\chromedriver.exe");
 System.setProperty("webdriver.chrome.driver",Chromedriver.getAbsolutePath());
 ChromeOptions options = new ChromeOptions();
 options.addArguments("start-maximized");
 driver = new ChromeDriver(options);
 baseUrl="http://www.wikishown.com";

}

//COUNT NO OF LINKS IN A WEBPAGE
 @Test
 public void Countlinks() throws InterruptedException{
 driver.get(baseUrl);
 Thread.sleep(2500);
 try{
 List lists = (List) driver.findElements(By.tagName("a"));
 int Linkscount = lists.size();
 System.out.println("Number of links in a webpage is "+Linkscount);

}catch(Exception e){
 e.printStackTrace();}
     }
  @AfterClass
  public void closeBrowser(){
  System.out.println("Browser is closed");
  driver.close();
  }
}


Incase it is very helpful and knowledgable please share it as well as provide your valuable suggestions.Thank you for reading my website.

Test Results:

Started InternetExplorerDriver server (64-bit)
2.53.1.0
Listening on port 44910
Only local connections are allowed
Page title of websiteLearn Selenium Automation Testing
Page title is matching with Expected Results - Test Case is PASS
Number of links in a webpage is 52
IE Browser is closed
PASSED: openSite

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


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Must Read

Selenium WebDriver Architecture
Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium
Mouse Hover action in Selenium
Selenium Limitations

How to run Selenium script in IE Browser

How to run Selenium script in IE Browser post gives you clear explanation to run or execute selenium webdriver test scripts in Internet Explorer i.e IE browser.To run  Selenium script in IE Browser you require InternetExplorerDriver which it is a standalone server.In order to run your Selenium script you have to download Internet Explorer Driver to run your selenium scripts,just go to Selenium site and search for Internet Explorer Driver Server here you will find 32 bit version and 64 bit version to download as per your machine/Laptop.

Please follow below steps to run Selenium script in IE Browser and create test scripts in selenium webdriver. Please unzip the IEdriver and you will find IEDriverServer.exe file from zip file as below
Run selenium script in IE browser


Just you need to write this extra code to open or run your selenium test scripts in IE Browser

System.setProperty("webdriver.ie.driver", "F:/Java_Apps/IEdriverServer.exe");
driver = new InternetExplorerDriver();

Please find below example to run Selenium script in IE Browser ,i have used my blog i.e http://learn-selenium-automation-testing.blogspot.in/ to execute the test script with TestNG annotation,please read TestNG Tutorial.

package com.seleniumpractice.reports;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class InternetExplorer {

 
 public WebDriver driver;
 String baseUrl = "http://learn-selenium-automation-testing.blogspot.in/"; 
 
 @BeforeTest
 public void openBrowser(){
  
 System.setProperty("webdriver.ie.driver", "F:/java_apps/IEdriverServer.exe"); 
 driver = new InternetExplorerDriver();
 driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
  
 }
 @Test
 public void openSite(){
  driver.get(baseUrl);
  //Verify whether exact page is open or not
  //Store page title in one String
  String actual_title = driver.getTitle();
  System.out.println("Page title of website"+actual_title);
  //If condition to verify page title
  String Expected_title = "Learn Selenium Automation Testing";
  
  if(actual_title.equals(Expected_title)){
System.out.println("Page title is matching with Expected Results - Test Case is PASS");
   
  }else{
System.out.println("Page title is not matching with expected results - Test Case is Fail");
  }
  
 }
 
 @AfterClass
 public void closeBrowser(){
  //Close open browser
  driver.close();
  System.out.println("IE Browser is closed");
 } 

}


Run the Test script as TestNG Test as Right click on Script - Run As - TestNG Test,you will see selenium test script execution in IE browser,most of the people facing speed issue in Internet explorer browser to open any website,in case selenium webdriver not finding page title in given time i.e 30 seconds,it will give you the error and it will fail the Test.

Test Results:

Once you execute the script it will display Test Results as below.

Started InternetExplorerDriver server (64-bit)
2.53.1.0
Listening on port 14471
Only local connections are allowed
Page title of websiteLearn Selenium Automation Testing
Page title is not matching with expected results - Test Case is Fail
PASSED: openSite

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


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

how to run selenium scripts in IE browser



I hope you got good information about how to run Selenium script in IE Browser with the help of IEDriver Server i.e internet explorer driver server,please provide your valuable comments and suggestions on this post.



Selenium Limitations

Selenium is a functional web automation testing tool and We can have wait commands to handle AJAX calls.But it is having some Selenium limitations those are

Selenium Limitations

1.Not support for Captcha/Barcode readers.
2.Unable to use proxy to open other websites.
3.Not support for Flash applications.
4.Problems with java applets.
5.Huge challenges with IE browser to automate the application which supports IE browser.
6.Don’t have built in plugins for REPORTS Generation, we need to use JUNIT,TESTNG etc.

Also Read

Selenium webdriver Architecture
Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium
Mouse Hover action in Selenium

Selenium Introduction

Selenium is an open source tool which is used to Automate Web applications which is Application under Test(AUT) in order to perform Regression Testing of applications.Selenium is a suite of tools which is automate web browsers in different platforms,supports many languages,runs in different operating systems.Selenium suite is a combination of four tools.



Selenium Components:

Selenium is suite tools which are

1.Selenium IDE
2.Selenium RC(Remote Control)
3.Selenium WebDriver
4.Selenium Grid

Selenium doesn't support automate to windows applications and selenium not support for 2 - tier environment ,it supports 3 - tier environment applications.

Selenium IDE:

Selenium IDE full form is Integrated Development Environment,IDE is a firefox plugin which is a free plugin for firefox browser.Selenium IDE useful in record and playback of web applications.IDE providing options to convert recorded script into different languages and ide can convert script to below languages.

In order to convert to different languages ,you need to enable "Enable Experiment features" in Options.

  • C#/NUnit/WebDriver
  • C#/NUnit/Remote Control
  • Java/Junit 4/WebDriver
  • Java/TestNG/WebDriver
  • Java/Junit 4/WebDriver Backed
  • Java/Junit 4/Remote Control
  • Java/Junit 3/Remote Control
  • Java/TestNG/Remote Control
  • Python 2/unittest/WebDriver
  • Ruby/Test:Unit/WebDriver

Selenium IDE Drawbacks:

1.Cross browser testing is not possible
2.Data-driven Testing is not support.
3.Not possible to generate reports
4.Need to open Browser before opening Selenium IDE.

You can export recorded test cases to above different languages from File - Export Test Case As.

Selenium RC:

Selenium RC full form is Remote Control,Selenium RC also known as Selenium 1 before launching Webdriver Selenium Rc used in most of the web application automation.Selenium RC directly not communicate with the browsers ,first Selenium RC communicate with Selenium standalone server then it will communicate with different browsers and it will execute selenese commands.

Selenium RC drawbacks:

1.Selenium RC doesn't communicate directly with browsers.
2.Selenium RC scripts will run only on javascript injection support browsers.
3.Selenium RC test execution takes more time.
4.Inorder to run Selenium RC first you need to start Selenium RC server.

Selenium Webdriver:

Selenium Webdriver also called as Selenium 2,which is widely using to automate different web applications.Selenium Webdriver directly communicate with different browser in order
to execute Selenium Webdriver Test scripts.Selenium Webdriver doesn't require any selenium server.Please read Selenium Webdriver Architecture for more details.Latest Selenium version is
Selenium 3.0.1 java language.

Selenium Supports drivers:

1.Mozilla Geckodriver
2.Google Chrome Driver
3.Opera drivers
4.Internet Explorer Driver
5.Safari Driver
6.ios-drivers
7.Appium

Also Read

Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium
Mouse Hover action in Selenium




Mouse hover action in Selenium Webdriver

Mouse hover action in Selenium Webdriver,While working with web application menus you will face a problem that mouse hover,once mouse hover then only remaining menus will be displayed.In this post you will learn Mouse hover action in selenium webdriver using Web elements ,Actions classes in Selenium Web Driver.Below are the way of doing this is by using Action in class.

Mouse hover action in Selenium WebDriver


Mouse hover action in Selenium Webdriver

Method 1:

Here directly using link Text to check mouse hover for main menu or sub menu to identify the elements in webpage.

WebElement element = driver.findElement(By.linkText("More.."));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("SQL")).click();

Some times it will not work then we can use another method as below to select SQL link from More.. menu according to above menu.

Also Read

Datadriven Framework using selenium
Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium

For some applications mouse over will work upto certain fraction of seconds at that situation we can go for below method easily to identify the elements.This method will work deffinately with the help of action.moveToElement(element).click().build.perform

package com.gmail.account;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.apache.tools.ant.taskdefs.Exit;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class MouseOver{

WebDriver driver;
String baseUrl;

@Test
public void mouseHover(){

driver = new FirefoxDriver();
String baseUrl = "http://www.wikishown.com";
driver.get(baseUrl);
driver.manage().window().maximize();
//Use Action
Actions action = new Actions(driver);
//Mouse over on elements using WebElments
WebElement element = driver.findElement(By.linkText("More.."));
//Now mouse should move to particular element
action.moveToElement(element).click().build().perform();
Thread.sleep(2000);
//Identifying the SubMenu and click on Subbmenu
action = new Actions(driver);
WebElement subelement=driver.findElement(By.linkText("SQL"));
//Thread.sleep(5000);
action.moveToElement(subelement).click().build().perform();

}

}

Run above script as Right Click on Script - Run As  - TestNG Test.

Conclusion:

I am expecting method 2 is very useful in your projects,in case it is working please provide your valuable comments and suggestions and please feel free to contact me through comment.Thank you for reading.

Selenium Data Driven Framework step by step

Welcome to Selenium Tutorials, in this Selenium Data Driven Framework step by step giving clear details about Data Driven Framework with selenium with real time examples.Most of the frameworks data driven is most important in order to run the script for positive and negative test cases and handling validation message.Framework can be finalized based upon web application (AUT) you are testing.If you are doing testing of big applications then you can go with Data Driven framework and keyword driven framework.

What is Data driven?

Data driven testing is nothing but testing the application with multiple set of data in order to verify how application behaves with positive and negative scenarios. Data driven testing can be done with the help of Excel,Text files,Csv files and Databases.In this post i am using Excel files to drive the application with multiple set up test data.Please follow below simple steps to create Data Driven Framework in Selenium WebDriver.

Pre-requisites:

Below are the important pre requisite for creating Selenium Data Driven Framework step by step,please make sure you should have below details.

1.Selenium Webdriver
2.jxl jar
3.Excel files as a format of xls
4.Dataprovider in TestNG
5.TestNG Library

Excel file:

Here i'm using excel file for multiple set of data to drive the application for positive and negative scenarios and created the Test Scripts with TestNG annotations,those are

1.@Test
2.@DataProvider

Test Data excel file


Please read TestNG Tutorials for good understanding of TestNG annotations. Please find below Selenium Script for Data driven framework creation.

Selenium Script:

 package simple_package;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.concurrent.TimeUnit;
 import org.openqa.selenium.Alert;
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.chrome.ChromeDriver;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 import jxl.Cell;
 import jxl.Sheet;
 import jxl.Workbook;
 import jxl.read.biff.BiffException;

 public class Customer_Registration {

  WebDriver driver;

  @Test(priority = 1)
  public void login() throws InterruptedException {

   driver = new FirefoxDriver();
   driver.manage().window().maximize();
   driver.get("http://www.wikishown.com");
   System.out.println("Browser is opened and wikishown url in entered.");

   driver.manage().window().maximize();
   Thread.sleep(2000);

   driver.findElement(By.id("userId")).sendKeys("xxxxxxxxx");
   driver.findElement(By.id("passId")).sendKeys("xxxxxxxx");
   driver.findElement(By.id("submit")).click();

   System.out.println("Wikishown My Account page is loaded");
  }

  //Calling Excel file input column names using String

  @Test(priority = 2, dataProvider = "Cust_Reg")
  public void customer_regis(String Mobileno, String Firstname, String Lastname) throws Exception,
   BiffException, IOException {

    driver.findElement(By.name("searchMobileNo")).clear();
    driver.findElement(By.name("searchMobileNo")).sendKeys(Mobileno);

    Thread.sleep(3000);
    driver.findElement(By.id("searchBtn")).click();

    System.out.println("search button is clicked");
    Thread.sleep(2000);

    driver.findElement(By.id("fname")).sendKeys(Firstname);
    driver.findElement(By.id("lname")).sendKeys(Lastname);

    driver.findElement(By.id("validateBtn")).click();
    System.out.println("Validate Button is clicked");
   }

  //Identification of Excel file
  @DataProvider(name = "Cust_Reg")
  public Object[][] CustRegistration() throws Exception {
   FileInputStream filepath = new FileInputStream("E:\\Automation_Testing\\TestData.xls");

   Workbook wb = Workbook.getWorkbook(filepath);
   Sheet sheet = wb.getSheet("Cust_Data");

   int row = sheet.getRows();
   System.out.println("number of rows" + row);
   int column = sheet.getColumns();
   System.out.println("number of columns" + column);
   String Testdata[][] = new String[row - 1][column];
   int count = 0;

   for (int i = 1; i < row; i++) {
    for (int j = 0; j < column; j++) {
     Cell cell = sheet.getCell(j, i);
     Testdata[count][j] = cell.getContents();
    }
    count++;
   }
   filepath.close();
   return Testdata;
  }
 }


Must Read

Launch Firefox Browser using GeckoDriver
Selenium Xpath Tutorial
Verify element is enable in Selenium
Read Data From properties file using Selenium
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium

In above script i have usesd below parameters

1.String Mobileno
2.String Firstname
3.String Lastname

these are the column names in the excel file which are using for Test Data as above image and we are passing these parameters in "customer_regis" method with the help of Dataprovider method as used in "public Object[][] CustRegistration()" method where i am calling Test data excel file with the help of FileInputStream filepath = new FileInputStream("filepath") and getting particular worksheet where data is stored ,calling that sheet in order to count no of rows ,no of columns to run until the end of the test data in file with the help of for loop as seen in CustRegistration method.

Now calling CustRegistration method i have declared Dataprovider name as above and using this name in public void customer_regis() method in order to pass the values in place of static data as below.

driver.findElement(By.id("fname")).sendKeys(Firstname);
driver.findElement(By.id("lname")).sendKeys(Lastname);

1.Save above script and replace with your AUT application URL and replace all your elements.
2.Close the excel sheet
3.Run the script with TestNG Test.

You will see application will run with multiple set up test data i.e Data driven Testing.Thank you for reading,Please provide your valuable comments on this topic so that i will modify the details more efficient.Please implement for your web application here i have given the code.

How to handle authentication required in selenium webdriver

Selenium web driver provides options to handle authentication required,here we are using Google chrome browser for authentication.While working with separate Browsers i.e IE,Fire Fox and Chrome we will face Authentication problems in order to open web applications which is under test whether it may be QA or UAT . In order to overcome this problem ,please follow the below easy code.

ALSO READ

TestNG Classpath error
Session ID is null using webdriver after calling quit
How to send extent reports in email with screenshots
Write Test Cases PASS or FAIL using Selenium
Read data from properties file in selenium
Run Selenium scripts using Command Line
Run Selenium Scripts using Runnable JAR
TOP Selenium Interview Questions asked in MNC
How to Send attachments in Jenkins emails
Selenium XPATh tutorial step by step


How to handle authentication required in selenium webdriver:

1.Robot Object
2.KeyEvents :Useful for Keyboard operations
3.Username and Password in order to authenticate the Pop Up window.

Authentication Script:


package com.gmail.account;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

//Create Class
public class Selwebddriver {
//Declare Webdriver ,baseUrl
WebDriver driver;
String baseUrl;

@BeforeClass
public void setup(){

//Initialize the Chromedriver with exe file
File ChromeDriver = new File("F:\\Java_Applications\\Zip Files\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver",ChromeDriver.getAbsolutePath());

//TO maximize the chrome window
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
driver = new ChromeDriver(options);

//Declare the url
baseUrl="http://www.gmail.com";

}

@Test
public void Confirmation() throws AWTException {

driver.get(baseUrl);

//Create Robot object
Robot rb = new Robot();
//Save the Username in user string
StringSelection user = new StringSelection("admin");
//User which replace with entered user name
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(user, null); //Copy Username data using Ctrl+v as below rb.keyPress(KeyEvent.VK_CONTROL); rb.keyPress(KeyEvent.VK_V); //Now release the KEYs rb.keyRelease(KeyEvent.VK_V); rb.keyRelease(KeyEvent.VK_CONTROL); //Press TAB to enter password rb.keyPress(KeyEvent.VK_TAB); //Now Release the TAB key rb.keyRelease(KeyEvent.VK_TAB); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Same above code for Password StringSelection passwd = new StringSelection("admin"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(passwd, null); //passwd which replace with entered password //Copy password data using Ctrl+v as below rb.keyPress(KeyEvent.VK_CONTROL); rb.keyPress(KeyEvent.VK_V); //Now release the KEYs Ctrl+v as below rb.keyRelease(KeyEvent.VK_V); rb.keyRelease(KeyEvent.VK_CONTROL); //Press Enter using VK_ENTER key rb.keyPress(KeyEvent.VK_ENTER); //Now Release the key ENTER rb.keyRelease(KeyEvent.VK_ENTER); driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); System.out.println("Authentication is successfull....WebSite is opened."); } }

Test Results:

Authentication required using selenium webdriver


Please provide your valuable suggestions,feedback or comments in case you like this post "How to handle authentication required in selenium webdriver".Thank you for reading.

How to pass WebDriver instance to other class in Selenium

In this post we are going to learn How to pass the Web Driver instance to other Class in Selenium web driver?.In this post i am using Selenium Web Driver,Java language and Test NG,for more details on Selenium TutorialsTestNG please read my tutorials,so that you can get more knowledge.

Please follow below steps

1.Create Selwebddriver.java class
2.Create other class here I am using AppConfirmation.java as below.





Selwebddriver Class:

//Package Name
package com.gmail.account;
import java.io.File;
import org.openqa.selenium.WebDriver;
//Chrome Driver
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
//Test NG Annotation
import org.testng.annotations.BeforeClass;
//Class Name
public class Selwebddriver {
//Declare Webdriver variables
WebDriver driver;
String baseUrl;
//Initializing Selenium Webdriver Before Class
@BeforeClass
public void setup(){
//Iam using Chrome Browser
File ChromeDriver = new File("F:\\Java_Applications\\ZipFiles\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver",ChromeDriver.getAbsolutePath());
//Chrome Options to maximize full window
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
driver = new ChromeDriver(options);
baseUrl="http://www.gmail.com";
}
}

Now we have to use Selwebddriver Class instances in second class as below.

AppConfirmation Class

//We are using Selwebdriver instance with extends keyword
public class AppConfirmation extends Selwebddriver {
//Test NG Annotation where we are executing Test cases using Test annotation.
@Test
public void Confirmation() throws AWTException {
reports = new ExtentReports("E:\\Automation_Testing\\GmailAuto\\TestResults\\Testresults.html",true);
ExtentTest test = reports.startTest("Verify GmailLogin page");
//Open Specified application URL with below code
driver.get(baseUrl);
test.log(LogStatus.PASS, "Gmail Login page is opened");
}
}

Now run AppConfirmation Class as Run as Test NG with right click on AppConfirmation Class,it will automatically calls Selwebdriver instances and open the browser.In case you like my post and idea about How to pass the Web Driver instance to other Class in Selenium ,please provide your valuable comments, suggestions , feedback. Thank you for reading.

What have you Learned?

1.Java extends keyword.
2.Use one class objects in another class ex:driver.
3.Create two classes and use driver instance to a number of classes.
4.TestNG tests annotations in different classes.

Must Read:

Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium

How to Generate Reports in Selenium using TestNG

How to Generate Reports in Selenium using TestNG,Welcome to Selenium Tutorials ,in this post i am going to explain How to Generate Reports in Selenium using TestNG using Extent Report jars.Here i am using extentreports-java-v2.41.0 ,this zip file can be downloaded from here.

How to Generate Reports in Selenium using TestNG

  1. Java Project. 
  2. TestNG Framework. 
  3. selenium-java-2.41.0 of all jar files. 
  4. Selenium WebDriver. 
  5. Extent Reports jars.
  6. Reports folder to save the Test Results.Lets create the reports in Selenium using TestNG with Extent Reports jars.

Create Java Project with any name ,i have created project name as SelPractise,in this project create Package name under Src folder.Under package create one class with any name ,Configure build path with all jar files of selenium-java-2.41.0/libs folder.Lets see the code below.



package com.cname.webapp.Advancereports;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class VerifySite {
 //Declare Web Driver variables
 private WebDriver driver;
 private String baseurl;
 //Declare Extent Reports
 private static ExtentReports reports;
 
 @BeforeTest
 public void setup() throws IOException{
 //initialize chrome driver for application to run
 File ChromeDriver = new File("F:\\Java_Applications\\Zip Files\\chromedriver.exe");
 System.setProperty("webdriver.chrome.driver",ChromeDriver.getAbsolutePath());
 driver = new ChromeDriver();
 baseurl="http://www.wikishown.com"; 
 
 }
 
 @Test
 public void VerifyHome() throws IOException{
 
 //Initiate Extent Reports
 reports=new ExtentReports("E:\\Tutorials\\SeleniumPractice\\Reports\\results.html",true);
 
 //Declare Start test name
 ExtentTest test = reports.startTest("Verify Home page"); 
 
 //Maximize the window
 driver.manage().window().maximize();
 test.log(LogStatus.PASS,"Browser is open and window is Maximimzed.");
 
 //Open Specified url in the browser
 driver.get(baseurl);
 test.log(LogStatus.PASS,"Web application is opened in Browser."); 
 
 //Get title of the Home page
 String title = driver.getTitle();
 
 //Verify page title with if condition 
 if(title.contains("Welcome to Future Bazaar - India's gifting bazaar")){
 
 test.log(LogStatus.PASS,"Home page title is displayed.");
 
 }else{
 test.log(LogStatus.FAIL,"Web application title is displayed.");
 } 
  //Ending the Test
 reports.endTest(test); 
 //writing everything to document
 reports.flush();
 driver.close();  
 }

Run above code  Run as Test NG Test where it will open Google Chrome browser , Maximize the window,Enter the specified URL ,Home page opens,Driver gets title of the page and verifies the title with if condition. By this above code you will generate beautiful Test results reports in html format ,here i have run for two test and it will display as below. 1.Extent Reports without Dashboard.

Extent Report with out Dashboard:

Generate Reports in Selenium


Extent Report with Dashboard:

Extent Report with Dashboard


Extent Report with Dashboard and Test names,Steps.

Extent Report with Test Names,Steps



Please provide your valuable comments on this post and please share my post.Thank you for reading my post and My Selenium Tutorials.

Read data from Properties file using Java Selenium webdriver

We can easily read properties from object repository file or some other files using object type properties,In this post example you will learn perfect knowledge about Read data from Properties file using Java Selenium.Please Read Selenium WebDriver Tutorial.Properties files are using in Java programming which is mainly using for configuration data in their project like data base configuration details,GUI Element data etc.In Selenium Test scripting you can use properties files to read the data from files to your Test scripts in order to maintain clean scripts and clear understanding of test scripts.

Read data from Properties file using Java Selenium webdriver
Properties file in Selenium WebDriver


Read data from Properties file using Java Selenium webdriver

In below example you will understand how to create properties file and read data from properties files ,please read full article to understand clearly and i have given brief explanation below the end of the code with each step so that you people can understand clearly.Let's see the below code.
package com.eu.examples;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Properties;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.Test;


public class PropertiesFilesSelenium {


//Read data from Properties file using Java Selenium

//OR= Object Repository:

public static WebDriver driver;

@Test

public void openBrowser() throws FileNotFoundException{


driver = new FirefoxDriver();

//using properties to create object

Properties property = new Properties();

//Call the file OR.propoeties file using FileInputStream

FileInputStream objFile = new FileInputStream</span></pre>
<pre><span style="font-size: medium;">("E:\\QTP Tutorials\\Selenium Automation\\ExtentUsages\\OR.properties");

//Load the properties File

try {

property.load(objFile);

} catch (IOException e) {

System.out.println(e.getMessage());

e.printStackTrace();

}


//Open Software Testing blogspot

driver.get(property.getProperty("baseURL"));

//Maximize the window

driver.manage().window().maximize();

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

System.out.println("Window is maximized");

//Click on Manual Testing menu

driver.findElement(By.xpath(property.getProperty("Manualtesting"))).click();

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

System.out.println("Clicked on Manual Testing menu");

//Click on QTP Tutorials

driver.findElement(By.xpath(property.getProperty("QTPTutorials"))).click();

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

System.out.println("Clicked on QTP Testing menu");

//Click on SeleniumTutorials

driver.findElement(By.xpath(property.getProperty("SeleniumTutorials"))).click();

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

System.out.println("Clicked on sELENIUM Testing menu");

//Click on LoadrunnerTutorials

driver.findElement(By.xpath(property.getProperty("LoadrunnerTutorials"))).click();

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

System.out.println("Clicked on Loadrunner Testing menu");


OUTPUT:

Once you run above program you will get below output in Eclipse console

Window is maximized
Clicked on Manual Testing menu
Clicked on QTP Testing menu
Clicked on sELENIUM Testing menu
Clicked on Loadrunner Testing menu
PASSED: openBrowser

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

Properties File

#Software Testing Application Object Properties#

baseURL=http://softwaretestutorials.blogspot.in

#Different Menu's Properties
Manualtesting=/html/body/div[4]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/div/ul/li[2]/a
QTPTutorials=/html/body/div[3]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/div/ul/li[3]/a
SeleniumTutorials=/html/body/div[3]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/div/ul/li[4]/a
LoadrunnerTutorials=/html/body/div[3]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/div/ul/li[5]/a

Read data from Properties file using Java Selenium Properties File Code Explanation:

Below details will give you brief details about above code in detail explanation,let's start understanding the code.

Properties property = new Properties();
In Above i have created one object under Properties() because wit this object you can load or read the properties file easily.

FileInputStream objFile = new FileInputStream("E:\\QTP Tutorials\\Selenium Automation\\ExtentUsages\\OR.properties");

FileinputStream in java is useful in reading the different files in order to get the data from specified file and here we are going to use this FileInputStream to load the file into our scripts.

try {
property.load(objFile);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

In order to load the FileinputStream file ,you can use above try catch block for load the file in order to avaoid IOException while executing the script.

driver.get(property.getProperty("baseURL"));

In order to read the data from Propoerties file just you need to use property.getProperty(String Key),here property is created object in properties i.e property and getProperty is a method to read the properties from property files.

Thank you for reading please share my post.