Get Inner HTML of Web Element
To get the inner HTML of a web element using Selenium in Java, call getAttrbibute("innerHTML")
on the Web Element object.
The following is a simple code snippet to get the inner HTML of web element element
.
</>
Copy
element.getAttribute("innerHTML")
getAttribute("x")
returns a String representing the value of the given attribute x
. Since we need the value for innerHTML attribute, we pass the string "innerHTML"
as argument to getAttribute()
.
Example
In the following program, we write Selenium Java code to visit WikiPedia Main Page, find the web element with the id "Welcome_to_Wikipedia"
, then get the inner HTML of this web element.
Java Program
</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyAppTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://en.wikipedia.org/wiki/Main_Page");
WebElement element = driver.findElement(By.id("Welcome_to_Wikipedia"));
String innerHTML = element.getAttribute("innerHTML");
System.out.println(innerHTML);
driver.quit();
}
}
Output
Welcome to <a href="/wiki/Wikipedia" title="Wikipedia">Wikipedia</a>
Screenshot