How to refresh webpage using Action class in selenium WebDriver?

Refresh webpage using Actions Class in Selenium WebDriver –
There are various ways to refresh webpage in selenium webdriver. One of them using Actions class.
Refresh WebPage using Actions class in Selenium WebDriver
Application can be refreshed in multiple ways. We can use

driver.navigate().refresh();
Method, or can send key F5.
Here, Web Page refresh can be achieved by using Actions class of the selenium WebDriver.
Below program explain this –
package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RefreshUsingActionsClass {

 public static void main(String[] args) throws InterruptedException {
  // TODO Auto-generated method stub
  
  WebDriver driver = new FirefoxDriver();
  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");
  
  //sleep the website for 4 seconds so that we can notice the refresh of web page
  Thread.sleep(4000);
  
  Actions act = new Actions(driver);
  
  //using below command we can refresh the webpage
  act.keyDown(Keys.CONTROL).sendKeys(Keys.F5).build().perform();
 }

}  

Difference between findElement and findElements in selenium WebDriver.

What is the difference between findElement() and findElements() in selenium WebDriver?

driver.findElement() and driver.findElements() both methods are used to find (locate) the WebElements. But as name suggest, they are different. Let us see the difference between them.
driver.findElement(): – 
 
            1.      Return single WebElement from the webpage.
         2.   If multiple WebElements with same location are present, then this returns first matching WebElement with specified locator.
            3.      If element is not found on the webpage, then it throws NoSuchElementFoundexception.
            4.      We can use WebElement methods on returned element again
Example – 

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://testing.webield.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.findElement(By.xpath("html/body/div[1]/div/div[2]/form/div[1]/div/input")).sendKeys("admin");

 driver.findElements(): –        
               
                  1.       Returns all (array of) matching elements with specified locator.
                  2.      findElements() is used to find the group of elements in to the list.
                  3.      This method returns List<WebElement>. That is the List of the WebElements.
                  4.      If no matching element is found, this method will return an empty List.
                 5.      As this method returns a list of WebElements, we have to get individual WebElement using for loop / iterator.
Example –

List<WebElement> l = element1.findElements(By.tagName("td")); 
System.out.println("Total elements present in table are: " +l.size());

for (int i = 0; i<l.size(); i++){
System.out.println("table contents: "+l.get(i).getText());

}

Hope this Helps!!!!

How to get Total Number of Rows and Columns in the Web table using Selenium WebDriver?

In this article i will talk about how to get Total Number of Rows and Columns in the Web table using Selenium WebDriver? Firstly let us get the basic understanding about web table.

Refer below post –

How to handle Dynamic Web Table using selenium Webdriver?

In above blog post, we learned how to get all data from web table. Now, let us see, how can we get the total number of rows and total number of columns in the web table.

Below is the HTML code for sample table.

Observe above HTML code for sample table. We know that, tagname <tr> is to indicate that, it is a row in the web table.

Tagname <tr> will be under tagname <tbody>

So, we need to get WebElement of <tbody> tag, so that we can get the count of <tr> tags & ultimately total number of rows in the web table.

So, Below is the sample code, with which we can get total number of rows in the web table.

WebElement TogetRows = driver.findElement(By.xpath("//table[@id='users_table']/tbody"));
List<WebElement>TotalRowsList = TogetRows.findElements(By.tagName("tr"));
System.out.println("Total number of Rows in the table are : "+ TotalRowsList.size());
In order to get total number of columns in the web table, what we need to do is, count total number of <td> tags in first <tr> tagname.

Below is the sample code, with which we can get total number of columns easily.

WebElement ToGetColumns = driver.findElement(By.xpath("//table[@id='users_table']/tbody/tr"));

List<WebElement> TotalColsList = ToGetColumns.findElements(By.tagName("td"));

System.out.println("Total Number of Columns in the table are: "+TotalColsList.size());
Hope this helps !!!

How to handle Dynamic Web Table using selenium Webdriver?

In this article, let us talk about how to handle dynamic web table using selenium webdriver. Before start, let us understand what is web table?
There are two types of Web Tables –
            1.       Static Web Table -> where the data is constant on the web page.
            2.       Dynamic Web table -> where the data changes dynamically based on the users request.

In a very simple language, Web table is nothing but the table present on the web page.

Now, since it is a table, it must have rows, columns, cell data, as like how we have in excel sheet.

So, when we deal with web table through selenium Webdriver, we must understand the internal table structure (how the table is created in HTML format?)

This is not very complex to understand. There are few HTML tag which defines the table.

Observe below screen shot. It is a dynamic web table.

If we see the HTML layout for this table, it is as below –

In above HTML structure, we can clearly see that, table has HTML tags like, table, thead, tbody, tr, td etc. Here –

table -> indicate that, it is a web table

thead -> includes the header of the table
tbody -> includes the body of the table.
tr -> indicate that, this is a row of the table.
td -> indicate that, this is the actual table data (as like cell data in excel).

So, this means, actual data of the web table is present under <td> tag. If you want to read this data from web table, then you should read data from <td> tag.

Let us see how can we do this.

Step1: Locate the WebElement where table is.

WebElement is nothing but HTML element, like dropdown, radio button, table, textbox etc. So, in order to get data from webtable, your first task is, to get the webElement of the table.Ex –

WebElement element1  = driver.findElement(By.xpath("//table[@id='users_table']"));

Step2: To get the list of table data

As we saw earlier, table data will be containted within tag <td>.
So, in order to get table data in to the list, we need to find all the elements by tagname <td> on your webelement.

Ex –

List<WebElement> l = element1.findElements(By.tagName("td"));


Step3: Get the data from List

Once you get data in to the List, by using above step, now we need to retrieve the data from list based on index. Here it is –

 for (int i = 0; i<l.size(); i++){
System.out.println("Total elements present in table are: " +l.size());
 System.out.println("table contents: "+l.get(i).getText());

                                }
Now, you can play with the data, as per demand in your test case.

On the similar basis, we can get total number of rows and total number of columns from the webtable. Explained in below post –

What is driver.close(); and driver.quit(); in Selenium WebDriver?

Driver.close and driver.quit are two different methods which are used to close the browser. But there is some difference in between them, as below –

1) WebDriver.Close() This method is used to close the current open window. It closes the current open window on which driver has focus on. If Suppose your Webdriver has opened more than one browser window, if you use driver.close(); then, it will close only 1 browser window on which driver is focused currently.

2) WebDriver.Quit() This method is used to destroy the instance of WebDriver. It closes all Browser Windows associated with that driver and safely ends the session. WebDriver.Quit() calls Dispose. If Suppose your Webdriver has opened more than one browser window, if you use driver.quit(); then, it will close all browser windows which are opened by that driver.

3) WebDriver.Dispose() This method closes all Browser windows and safely ends the session

You should use driver.quit whenever you want to end the program. It will close all opened browser window and terminates the WebDriver session. If you do not use driver.quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.
Conclusion:
Suppose if we are working with only one window, close () and quit () technically do exactly same thing that is closes the browser/window and releases the memory by quitting the driver. But if in our test, it opens another window while execution and we wish to close one of the windows, to continue execution; we can switch the focus to desired window and perform close action on it. On other hand if we are done with the execution and we want all the browser instances to be killed and release the memory, Quit command is recommended.
Example:
package com.aayushCorp.utilities;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;


public class LoginToAayushCorp { 

                WebDriver driver;

               
                @BeforeMethod

                public void Login() throws Exception {

 
                                driver =new FirefoxDriver();
                                 driver.navigate().to("https://www.google.co.i");
                                 driver.manage().window().maximize();
 
                }             

               

                @AfterMethod

                public void TearDown(){

                                driver.close();

                                driver.quit();

                }

 

}

What is Fluentwait? How to Achieve Fluent wait in Selenium?

FluentWait in Selenium WebDriverFluentWait is a customized type of Explicit Wait, here we can define polling period according to our need 2 Secs or 5 Secs, We can also configure the wait to ignore some exceptions like NoSuchElementExceptions.

This wait will check for the elements in the DOM for every 5 Secs until the elements found, if the element found within the period it breaks the search for the element and goes for the further action.

Fluent wait = Explicit Wait + frequency with which control need to be checked on application + exceptions to be ignored like  NoSuchElementExceptions.

Syntax: 
 

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);

Features of Fluent Wait:

In Fluent Wait we define a Maximum amount of time to wait for a condition. Also, we will be defining a Polling frequency time while declaring the Fluent Wait.Fluent Wait will be polling the web pages every Polling frequency time to verify the given condition.

Fluent Wait has Inbuilt exception handler, which will handle NoSuchElementException until given Maximum amount of time has breached.

Refer below Example for Fluent Wait –

package demoPackage1;

import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import javax.lang.model.element.Element;

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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.testng.annotations.Test;

import com.google.common.base.Function;


public class ExplicitWait {

  @Test
  public void FluentWaitTest(){
    
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://demowebshop.tricentis.com");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
       // Define fluent wait
       Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
           .withTimeout(30, TimeUnit.SECONDS)
           .pollingEvery(1, TimeUnit.SECONDS)
           .ignoring(NoSuchElementException.class);

       WebElement element = wait.until(new Function<WebDriver, WebElement>() 
       {
         public WebElement apply(WebDriver driver) { 
           return driver.findElement(By.xpath("//a[@class='ico-register']"));
         } } );
       element.click();
    
    driver.close();
    driver.quit();
  }
}

FluentWait in Selenium WebDriver

What is Explicit wait? How to Achieve Explicit wait in Selenium?

What is Explicit wait in Selenium WebDriver?

 

Explicit wait is a type of synchronization in selenium, which is webelement specific and not applied to driver for his life. Different elements on the page takes different times to load on the page, if we use implicit wait for 10 Sec there is no guarantee that all the elements loaded within 10 sec, some elements may take more than 1 minute, in such conditions Explicit waits can be used to wait for that particular element.
Explicit Wait in-Selenium-Webdriver
We can tell the tool to wait only till the Condition satisfy. Once the condition is satisfying, the tool proceed with the next step. This can be done with WebDriverWait in conjunction with ExpectedConditions Class.
Logic: –
It is applicable to the given control and waits to the maximum amount of time or move forward in case the given condition is met.

We are explicitly making the execution of selenium code to wait, for a certain condition to occur before, proceeding further in the code.

Syntax:

WebDriverWait.until(condition-that-finds-the-element(ExpectedCondition))

WebDriverWait by default calls the Expected Condition every 500 milliseconds until it returns successfully. Expected condition can be in the form of like:
button is disabled/enabled
textbox is visible
alertispresentExample for Explicit Wait

package demoPackage1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class ExplicitWait {

  @Test
  public void ExplicitWaitTest(){
    
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://demowebshop.tricentis.com/register");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
    //define webdriver wait statement with time specified
    WebDriverWait wait = new WebDriverWait(driver, 10);
    
    //apply the wait for specific element. Below statement will wait for element to be present till 10 sec as specified by above
    wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.xpath("//a[@class='ico-register']"))));
    
    driver.close();
    driver.quit();
  }
}

 

Explicit Wait in Selenium WebDriver

Hope This Helps !!!!

What is Firefox profile, Need of Firefox profile?

What is Firefox Profile?
When we install Mozilla Firefox, Firefox creates a default profile, it contains a collection of bookmarks, extensions, passwords, history, preferred home page when you open browser, and another browser setting etc. …,
                We can customize this Firefox profile as per our automation testing need.  So, one can say like Firefox profile is nothing but different user is using Firefox.
Why do we need to Set Firefox Profile in Selenium WebDriver? 
Default Firefox contains a collection of bookmarks, browser settings, extensions, passwords, and history; in short, all of your personal settings.
When you trigger selenium with this browser you test become slow and unreliable. To make it lighter we generally create a custom profile which loads only required plugins and extensions with predefined settings.
In order to run all test successful, we need a browser which –
  • Loads easily (very lightweight profile
  • Proxy setting (if required)
  • SSL certifications handling (if required)
  • Company specific username and password to start browser (if required)
How to create Firefox Profile in Selenium WebDriver?
Let us assume that you wanted to have google as the startup page for Firefox. To do this we will need to update the “browser.startup.homepage” preference.
Follow below steps to add a website as your homepage:
1. Let’s first start by creating the FirefoxProfile object.
2. Now we will set the preference by using the below method.
3. To get the profile to be used, we need to pass it in to the driver. To do this, we need
to do the following:
FirefoxProfile ffprofile= new FirefoxProfile();

profile.setPreference("browser.startup.homepage","http://www.google.com");

WebDriver driver = new FirefoxDriver(ffprofile);

That’s it, this is all we can set Firefox profile.

Let us see some examples where we can use this Firefox Profile setting.

Below two articles explain the real time use of Firefox profile –

How to handle proxy setting using selenium Webdriver? 

How to Handle SSL Untrusted Connection in Selenium WebDriver ?

How to handle proxy setting using selenium Webdriver?

 In this article, i will talk about How to handle proxy setting using selenium Webdriver?
Suggested Article to read: What is Firefox profile, Need of Firefox profile?

If we try to access some secure application, we get proxy related error many times and manually we need to update the proxy there. But what if we are automating that secure application? Our automation code should handle this.

Some applications have also issues related to SSL certification error. We again do that manually by accepting & confirming the certificate. But again, what if this encounter when we automate application using selenium Webdriver?
In this post, let’s talk about how to handle proxy setting using selenium Webdriver?
While setting up the proxy, note that there are different values for network.proxy.type , which we need to set based on our need. Here are some values –
0 – Direct connection (or) no proxy.
1 – Manual proxy configuration
2 – Proxy auto-configuration (PAC).
4 – Auto-detect proxy settings.
5 – Use system proxy settings.
Below 4 steps explain how can we handle proxy setting via selenium
Step1: Create the FirefoxProfile object.
Step2: Set preference for network.proxy.type
Step3: Set preference for network.proxy.http
Step4: network.proxy.http_port
    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("network.proxy.type", 1);

    profile.setPreference("network.proxy.http", "proxy.domain.example.com");

    profile.setPreference("network.proxy.http_port", 8080);

    profile.setPreference("network.proxy.ssl", "proxy.domain.example.com");

    profile.setPreference("network.proxy.ssl_port", 8080);

    WebDriver driver = new FirefoxDriver(profile);

That’s it, this should handle the updated proxy in code.

Hope this helps. Drop your comments.

How to Handle SSL Untrusted Connection in Selenium WebDriver ?

In this article, i will talk about how to handle SSL Untrusted connection in selenium webdriver.
Suggested Article to read: What is Firefox profile, Need of Firefox profile?

Handling SSL Untrusted Connection in Selenium WebDriver

Some applications have issues related to SSL certification error. We again do that manually by accepting & confirming the certificate. But again, what if this encounter when we automate application using selenium Webdriver?
Using profiles in Firefox we can handle accept the SSL untrusted connection certificate. Profiles are basically set of user preferences stored in a file.
Let’s consider the Firefox browser to create a new profile and set the following:
Handle Untrusted certificate (SSL Certificate error) in Firefox
FirefoxProfile profile = new FirefoxProfile();

profile.setAcceptUntrustedCertificates(true); 

profile.setAssumeUntrustedCertificateIssuer(false);

WebDriver driver = new FirefoxDriver(profile);

Handle Untrusted certificate (SSL Certificate error) in Chrome
To Handle SSL certification error in chrome, we need to Create object of DesiredCapabilities class. Basically, the DesiredCapabilities help to set properties for the WebDriver. The DesiredCapabilities class tells the Webdriver which environment we are going to use for test execution.
DesiredCapabilities cap=DesiredCapabilities.chrome();

// Set ACCEPT_SSL_CERTS  variable to true

cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

// Set the driver path

System.setProperty("webdriver.chrome.driver","Chrome driver path");

// Open browser with capability

WebDriver driver=new ChromeDriver(cap);

Handle Untrusted certificate (SSL Certificate error) in IE

// Create object of DesiredCapabilities class

DesiredCapabilities cap=DesiredCapabilities.internetExplorer();

// Set ACCEPT_SSL_CERTS  variable to true

cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

// Set the driver path

System.setProperty("webdriver.ie.driver","IE driver path");

// Open browser with capability

WebDriver driver=newInternetExplorerDriver(cap);

Hope this helps ….