About this lesson
getPageSource in Selenium Java: read the current HTML of the page
Learn Selenium JavaAdvancedAdvanced Topics
How it works
driver.getPageSource() returns the page's HTML as one String. It is the current DOM serialised as markup, not the file the server first sent: an element added by JavaScript after load is included, while text typed into an input is not, because typing changes the field's live value and not its value attribute.
Hidden elements are in the source because they are in the DOM. That is why a source check finds invisibleField even though the field is not displayed, and why a source check is weaker than isDisplayed() when you care what a user sees.
String.contains() is case-sensitive, so a search for a lower-case version of an id finds nothing. On Text Fields the source is about ten thousand characters long and starts with the html tag.
About the assignment
On Text Fields you read the page source once and run three checks on that string: whether it mentions two field ids from the task, and whether it has any content at all.
What you will do
- Call
getPageSource()and keep the result in aString. - Use
contains()for each id and print each result with the labels the task shows. - Print whether the source's
length()is greater than zero with the last label.
Common mistakes
Using the source to check visibility
A hidden element is in the source too, so its presence there does not mean a user can see it.
Searching for typed text
Text typed into an input is not written into the HTML, so it never shows up in the source.
Calling getPageSource() for every check
Each call fetches the whole page again. Read it once and reuse the string.
In a real test suite
Page source checks are handy for meta tags, structured data and analytics snippets that have no visible element, and for saving the HTML next to a screenshot when a test fails.
Lesson 69 checked dynamic state. This is the last Selenium Java lesson; to keep practising, try any of these calls on your own pages in the online compiler.
Related lessons
- JavaScript Executor - Get ValuesRead DOM details directly with JavaScript instead of searching the HTML string.
- isDisplayed() - Check Element VisibilityCheck visibility, which the source cannot tell you.
- Take Viewport ScreenshotSave a screenshot alongside the source when a test fails.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/TextFields");
// TODO: Get page source
// TODO: Check if it contains certain strings
// TODO: Print results
driver.quit();
}
}