How to get HTML code of a WebElement in Selenium?

SeleniumAutomation TestingTesting ToolsHTML

We can get the html code of a webelement with the help of Selenium webdriver. We can obtain the innerHTML attribute to get the HTML content of the web element.

The innerHTML is an attribute of a webelement which is equal to the content that is present between the starting and ending tag. The getAttribute method is used for this and innerHTML is passed as an argument to the method.

Syntax

String s = element.getAttribute('innerHTML');

Let us see the below html code of an element. The innerHTML of the element shall be < You are browsing the best resource for <b>Online Education</b>.

Example

Code Implementation

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
public class HtmlCodeElement{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("h4"));
      // obtain the innerHTML with getAttribute method
      String s = l.getAttribute("innerHTML");
      System.out.println("HTML code of element: " +s);
      driver.close();
   }
}

Output

raja
Published on 26-Oct-2020 11:33:24
Advertisements