How to get page source as it is in browser using selenium?

SeleniumAutomation TestingTesting Tools

We can get page source as it is in browser using Selenium webdriver using the getPageSource method. It allows us to obtain the code of the page source.

Syntax

String p = driver.getPageSource();

We can also obtain the page source by identifying the body tag with the help offindElement method and then apply the getText method on it. The parameter By.tagName is passed as a parameter to the findElement method.

Syntax

WebElement l= driver.findElement(By.tagName("body"));
String p = l.getText();

Example

Code Implementation with getPageSource

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get ("https://www.tutorialspoint.com/about/about_careers.htm");
      //get page source
      String p = driver.getPageSource();
      System.out.println("Page Source is : " + p);
      driver.close();
   }
}

Code Implementation with body tagname

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrcBody{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //get page source with getText method
      WebElement l= driver.findElement(By.tagName("body"));
      String p = l.getText();
      System.out.println("Page Source is : " + p);
      driver.close();
   }
}
raja
Published on 06-Apr-2021 08:09:29
Advertisements