I'm logging into the page using this function:

    public static void login() {
       driver.findElement(By.name("username")).sendKeys("username- login");
       driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

The login is successful and now i'd like to verify this by checking for certain elements on the landing page as follows:

    public static void testLogin(WebDriver driver) {
       String pageSource = driver.getPageSource();
       //Assert.assertTrue("Login was not successful!", pageSource.contains("Welcome to the page!"));

Everything works except for the fact that when i display the source code on the console, it is the source code of the login page (previous) and i'm hence the Assert is false.

Can anyone point me in the right direction?


I have accepted the answer from the_coder because it led me to this solution: I used WebDriverWait to wait until a specific element is present on the page before saving the source code into a String.

 WebDriverWait wait = new WebDriverWait(driver, 10);  
 wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(.,'Welcome to the page!')]")));
  • welcome to SQA! I'm not exactly sure what your question is. Are you asking why does your console print the previous pages code? Maybe you could post the console print? Jan 19, 2017 at 17:14
  • I'd like to verify that my login is successful by checking for the presence of certain elements on the landing page. I'm checking for this elements by storing the source code of the landing page in a string and looking if the string contains "Welcome to the page!", which is supposed to be shown upon successful login.
    – Antoine089
    Jan 20, 2017 at 7:45
  • 1
    Yes, I think the wait is the best solution, always wait for key elements to show or hide (e.g. loader indicators). Jan 20, 2017 at 8:25
  • import time give it a pause in between. Mar 1, 2019 at 6:57

1 Answer 1


You may be getting the previous page source code because the getPageSource() method is called before the page arrives to the page you want.

One thing I would like to suggest is before getting the pagesource of the webpage check whether you have navigated to the correct page like:

public static void testLogin(WebDriver driver) {
       String pageSource = driver.getPageSource();
       Assert.assertTrue("Login was not successful!", pageSource.contains("Welcome to the page!"));
         System.out.println("Not navigated to the correct page");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.