What is the usage of getPageSource() method in Selenium WebDriver

As name suggest, getPageSource() method is useful to get source of last loaded web page. Please note here, If web page is modified(by javascript) after loading of page then getPageSource() may return page source of before modified page. You can get whole page source using this method and then you can use it as per your requirement.

Let's see how getPageSource() method can be used in selenium test.

How to use getPageSource() method?
package TestPack;

import java.util.ArrayList;

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

public class testgetPageSource {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("http://only-testing-blog.blogspot.com/2014/09/temp.html");  
  
  //Prepared arraylist with names of animals to find them from page.
  ArrayList<String> animal = new ArrayList<String>();
  animal.add(0, "Lion");
  animal.add(1, "Elephant");
        
  //for loop is responsible to check animal names one by one from page
        for (String name : animal) { 
         //getPageSource().contains(name) will check and return true if animal name present and false if not present on page.
         boolean b1 = driver.getPageSource().contains(name);  
         if(b1) {
          //If animal name is present on page then print this message.
          System.out.println(name + " text is present on page.");
      }
         else
          //If animal name is not present on page then print this message.
          System.out.println(name + " text is not present on page.");
       }  

 }

}

Test Output : 
Lion text is present on page.
Elephant text is not present on page.

In above example you can see that Lion text is present on page so getPageSource().contains(name) has returned true and Elephant text is not present on page so getPageSource().contains(name) has returned false.


When you need getPageSource()?
Generally we are using getPageSource() method to verify if specific text or string is present on page and take decision to proceed further or not. i.e. I want to proceed test only if specific text or string is present on page else exit test.

No comments:

Post a Comment