Selenium accessing HTML source (Java)

Selenium accessing HTML source (Java)

In order to interact with the entire page source in Java, you need to use the WebDriver method getPageSource() . This code sample shows a basic operation that uses the method to search for a specific string.

String source = driver.getPageSource();

if(source.contains("Wikipedia")) {
  System.out.println("Wikipedia was found in page source");
} else {
  System.out.println("Wikipedia was not found in page source");
}

See Working Example


To get the HTML Code for a specific element you need to use the WebElement method getAttribute("outerHTML"). This will return a String containing the HTMl code of the page element and any child elements within.

E.g:

WebElement ele = driver.findElement(By.xpath("//*[@id='js-link-box-en']"));
String elementHTML = ele.getAttribute("outerHTML");
System.out.println(elementHTML);

See Working Example



Using Python

Leave a reply

Your email address will not be published. Required fields are marked*

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.