Get Outer HTML of Web Element

To get the outer HTML of a web element using Selenium in Java, call getAttrbibute("outerHTML") on the Web Element object.

The following is a simple code snippet to get the outer HTML of web element element.

</>
Copy
element.getAttribute("outerHTML")

getAttribute("x") returns a String representing the value of the given attribute x. Since we need the value for outerHTML attribute, we pass the string "outerHTML" 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 outer 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 outerHTML = element.getAttribute("outerHTML");
        System.out.println(outerHTML);	
        
        driver.quit();
    }
}

Output

<span class="mw-headline" id="Welcome_to_Wikipedia">Welcome to <a href="/wiki/Wikipedia" title="Wikipedia">Wikipedia</a></span>

Screenshot

Get Outer HTML of Web Element - Selenium