How to get content of entire page using Selenium?

SeleniumAutomation TestingTesting Tools

We can get the content of the entire page using Selenium. There are more than one ways of achieving it. To get the text of the visible on the page we can use the method findElement(By.tagname()) method to get hold of . Next can then use the getText() method to extract text from the body tag.

Syntax −

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

The next approach to get the content of the entire page is to use the getPageSource() method.

Syntax −

String l = driver.getPageSource();

Example

Code Implementation with <body> tag.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextContent{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.google.com/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element and input text inside it
      WebElement l =driver.findElement(By.tagName("body"));
      System.out.println("Text content: "+ l.getText());
      driver.quit();
   }
}

Output

Example

Code Implementation with getPageSource().

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageSrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",  "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.google.com/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // getPageSource() and print
      String l = driver.getPageSource();
      System.out.println("Page source: "+ l);
      driver.quit();
   }
}
raja
Published on 28-Aug-2020 12:53:38
Advertisements