• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Programming Languages
    • Java Tutorials
    • Python Tutorials
    • JavaScript Tutorials
  • Automation Tools and Different Tools
    • Web Automation
      • Selenium with Java
        • Selenium Basic
        • Selenium Advance
        • Selenium Realtime
        • Framework
        • Selenium Interview
        • Selenium Videos
        • Selenium with Docker
      • Selenium with Python
      • WebdriverIO
        • Selenium Webdriver C# Tutorial
      • Cypress
      • Playwright
    • TestNG
    • Cucumber
    • Mobile Automation
      • Appium
    • API Testing
      • Postman
      • Rest Assured
      • SOAPUI
    • testRigor
    • Katalon
    • TestProject
    • Serenity BDD
    • Gradle- Build Tool
    • RPA-UiPath
    • Protractor
    • Windows Automation
  • Automation For Manual Testers
  • Services
  • Online Training
  • Contact us
  • About me
  • Follow us
    • Linkedin
    • Facebook Group
    • Facebook Page
    • Instagram

Automation

Selenium WebDriver tutorial Step by Step

You are here: Home / Advance Selenium / Page Object Model using Selenium Webdriver and Implementation

Page Object Model using Selenium Webdriver and Implementation

March 5, 2020 by Mukesh Otwani 65 Comments

Firefox browser on mac using Selenium webdriver

In this post, we are going to discuss a very important topic or concept called Page Object Model, which you have to use in your project now or in the future if you are trying to create a framework.

Many companies use Page Object Model is a design pattern to store all locators and methods in separate Java class and we can use the same class in different test cases.

I get so many questions regarding Page Object Model framework but let me make it clear that Page Object model is just a design pattern, not a framework. There are multiple design pattern available for Java-like Singleton design pattern, Structural design pattern and so on. You can read about different design patterns in Java from this link. 

We will also use Page Object Model in Selenium to make our framework efficient and robust. I also have detailed video series on Hybrid Framework in Selenium on my youtube channel where we have used the same pattern. P

This is one the most important questions in interviews as well because now a day every company is trying to switch from traditional object repository to POM.

 

Page Object Model using Selenium Webdriver.

 

What is Page Object model using Selenium Webdriver?

1- It is a design pattern, which will help you to maintain the code and avoid code duplication, which is a crucial thing in Test automation.

2- You can store all locators and respective methods in a separate class and call them within the test in. The benefit from this will be, if any changes in web element locators then you do not have to modify the test simply modify the respective page and that all.

For example, earlier id was username and if id changed to uname then you do not have to change all the tests. You can use change the id in the respective page.

3- You can create a layer between your test script and application page, which you have to automate.

4- In other words, it will behave as Object repository where all locators are saved.

“Please don’t get confused if you are using Object repository concept which is property file, then do not use the Page Object model because both will serve the same purpose. You can use the file to store other configuration ”

 

Implementation of Page Object Model using Selenium Webdriver

If you want to implement the Page Object model then you have two choices and you can use any of it.

1 – Page Object model without PageFactory

2- Page Object Model with Pagefactory.

Personally, I am a big fan of Page Factory, which comes with Cache Lookup feature, which allows us to store frequently used locators in the cache so that performance will be faster. We will discuss both of them in this post and you can implement any of them based on your preferences.

Page Object Model using Selenium Webdriver without PageFactory.

Let’s take a very basic scenario so that you can relate to any application. Consider you have login page where username, password, and login button is present.

I will create a separate Login Page and will store three locators, and we will create methods to access them. Kindly refer below screenshot for reference.

Now I want to design a test case so that I can use the Login class, which I created and can call the methods accordingly.

This Login class can be used by all the test scripts, which you will create in future so if any changes happened in DOM then you have to update only Login Class not all the test cases.

 

I have created Youtube Video for the same

 

Program for Page Object Model using Selenium Webdriver without Page factory

package com.wordpress.Pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

/**
* @author Mukesh_50
* 
* 
* This class will store all the locator and methods of login page
*
*/
public class LoginPage 
{

WebDriver driver;



By username=By.id("user_login");
By password=By.xpath(".//*[@id='user_pass']");
By loginButton=By.name("wp-submit");


public LoginPage(WebDriver driver)
{
this.driver=driver;
}


public void loginToWordpress(String userid,String pass)
{

driver.findElement(username).sendKeys(userid);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();

}


public void typeUserName(String uid)
{

driver.findElement(username).sendKeys(uid);
}

public void typePassword(String pass)
{

driver.findElement(password).sendKeys(pass);
}

public void clickOnLoginButton()
{
driver.findElement(loginButton).click();
}
}

 

TestCase using Page Object Model using Selenium Webdriver

/**
* 
*/
package com.wordpress.Testcases;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

import com.wordpress.Pages.LoginPage;

/**
* @author Mukesh_50
*
*/
public class VerifyWordpressLogin 
{


@Test
public void verifyValidLogin()
{

WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize();

driver.get("http://demosite.center/wordpress/wp-login.php");

LoginPage login=new LoginPage(driver);



login.clickOnLoginButton();


driver.quit();

}


}

 

Page Object Model using Selenium Webdriver with Page Factory

Selenium has built in class called PageFactory, which mainly serve Page Object model purpose, which allows you to store elements in cache lookup.

The only difference, which you will get without PageFactory and with PageFactory, is just initElement statement.Let us check the code and will see what changes required for with PageFactory Approach.

Another YouTube video for Page Object model with Page Factory

 

Code for Page Object Model Using Selenium Webdriver using Page Factory

package com.wordpress.Pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class LoginPageNew 
{

WebDriver driver;


public LoginPageNew(WebDriver ldriver)
{
this.driver=ldriver;
}


@FindBy(id="user_login") 
@CacheLookup
WebElement username; 

@FindBy(how=How.ID,using="user_pass")
@CacheLookup
WebElement password;

@FindBy(how=How.XPATH,using=".//*[@id='wp-submit']")
@CacheLookup
WebElement submit_button;

@FindBy(how=How.LINK_TEXT,using="Lost your password?")
@CacheLookup
WebElement forget_password_link;


public void login_wordpress(String uid,String pass)
{
username.sendKeys(uid);
password.sendKeys(pass);
submit_button.click();
}


}

                                    Test Case using Page Factory



package com.wordpress.Testcases;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;

import com.wordpress.Pages.LoginPage;
import com.wordpress.Pages.LoginPageNew;

import Helper.BrowserFactory;

public class VerifyValidLogin 
{


@Test
public void checkValidUser()
{

// This will launch browser and specific url 
WebDriver driver=BrowserFactory.startBrowser("firefox", "http://demosite.center/wordpress/wp-login.php");

// Created Page Object using Page Factory
LoginPageNew login_page=PageFactory.initElements(driver, LoginPageNew.class);

// Call the method
login_page.login_wordpress("admin", "demo123");

}



}

I hope you have enjoyed the article and if yes then feel free to share this article with other and let me know your feedback in below comment section.

Filed Under: Advance Selenium Tagged With: Page Object Model using Selenium Webdriver.

Reader Interactions

Comments

  1. RANJAN V says

    June 18, 2021 at 9:57 AM

    Nice one)))

    Reply
  2. Manju says

    February 10, 2021 at 7:27 AM

    Hi Mukesh,

    Hope you are doing good…
    I have followed the same steps to create the POM. I am getting illegalStateException error even though used the chromedriver path correctly. I am using the chrome browser instead of firefox. please assist me where I am doing wrong.
    Chrome exe v88
    chrome v 88
    Selenium jar 3.41.59
    TestNG v7.3

    Reply
    • Mukesh Otwani says

      February 10, 2021 at 12:14 PM

      Hi Manju,

      Check whether path of the driver is correct and it includes file extension too. Let me know with your observations.

      Reply
  3. Shubhangi says

    May 11, 2020 at 7:07 AM

    Please help me understand how driver instance is passed as a constructor.I am a new bee to Java and Selenium.
    I understand that constructor is used to initialize variable to a value, we can achieve this using getters and setters.
    But unable to relate it(constructor) with WebDriver driver.
    Where in I have a different class of driver.
    Please help me with some diagram.

    Reply
    • Mukesh Otwani says

      May 11, 2020 at 11:21 AM

      Hi Shubhangi,

      Please go through this link https://www.youtube.com/watch?v=EZJiW5oM2Ks&list=PL6flErFppaj0WwNOMFeXPVlNCDuJyPYFi&index=3 Here I’ve explained the creation of page object class where I used driver object passed to the constructor.

      Reply
  4. Varsha Krishna Kumar says

    April 1, 2020 at 4:31 PM

    Hi mukesh ,
    A small clarification,
    In the POM eg without using page factory
    U have not called the logintowordpress(string username,string password) method from verifywordpresslogin class . Can u pls verify .
    Regards
    Varsha Krishna Kumar

    Reply
    • Mukesh Otwani says

      April 1, 2020 at 5:08 PM

      Hi Varsha,

      Thanks for bringing up this. I’ll update it…:) Please feel free to ask your doubts and queries

      Reply
  5. sonali says

    January 27, 2020 at 3:22 PM

    Hi Mukesh,

    How do i resolve this issue ….Element not clickable at point (1059, 232). Other element would receive the click

    Reply
    • Mukesh Otwani says

      January 27, 2020 at 5:23 PM

      Hi Sonali,

      Please check this link http://learn-automation.com/how-to-solve-element-is-not-clickable-at-pointxy-in-selenium/

      Reply
  6. Gaurav Arora says

    January 3, 2020 at 4:32 PM

    How can we apply waits in page object classes? I am applying webdriverwait and getting null pointer exception. can you take one example of clicking button and then waiting for any link to visible. I can use wait in normal framework but cannot in page object model.

    Reply
    • Mukesh Otwani says

      January 4, 2020 at 10:28 AM

      Hi Gaurav,

      I’ll post more contents related to framework soon…:)

      Reply
  7. mahesh says

    December 18, 2019 at 4:14 PM

    HI Mukesh

    Please consider now we have many class for page object.
    Ex: The second page is depends on first page and the third page is depends on second page,

    In this case we want to pass driver instance for all the page object class.

    should we create object for three different class or any other way is there .

    Please explain other solution without creating object for second class.

    How to get webdriver instance form page1.?

    Reply
    • Mukesh Otwani says

      December 18, 2019 at 7:57 PM

      Hi Mahesh,

      Page object model, usually driver needs to be passed as a parameter

      Reply
  8. ankit says

    December 4, 2019 at 10:17 PM

    Nice Sir, Very simple explaination that we required. Thnaks

    Reply
    • Mukesh Otwani says

      December 4, 2019 at 10:47 PM

      Hi Ankit,

      You’re always welcome to ask your doubts in automation…:)

      Reply
  9. Harshit says

    October 14, 2019 at 10:29 PM

    Which is better to implement Page object model using repository or using Page Factory?

    Reply
    • Mukesh Otwani says

      October 15, 2019 at 10:08 AM

      Hi Harshit,

      It’s better to use Page Factory

      Reply
  10. soni says

    June 29, 2019 at 1:55 PM

    Hi Mukesh,demo site is not working its giving below error

    demosite.center is currently unable to handle this request. HTTP ERROR 500.

    How to resolve this?

    Reply
    • Mukesh Otwani says

      June 29, 2019 at 2:55 PM

      Hi Soni,

      For time being, you can use this site https://opensource-demo.orangehrmlive.com/ for practice purpose.

      Reply
  11. Himansu says

    May 8, 2019 at 4:03 PM

    Yaa nice dude , its really help us …thanks for your dedications towards scripts

    Reply
    • Mukesh Otwani says

      May 8, 2019 at 4:52 PM

      Thanks Himansu…:)

      Reply
  12. suyash says

    April 22, 2019 at 2:24 PM

    How do I automate OTP login via selenium, I want to automate Login via OTP in a website

    Reply
    • Mukesh Otwani says

      April 23, 2019 at 12:30 AM

      Hi Suyash, avoid automating OTP scenarios.

      Reply
    • Mali says

      July 9, 2019 at 5:27 PM

      Hi Suyash/ Mukesh

      The below site will be helpful for authenticating OTP
      https://aerogear.org/docs/guides/AeroGear-OTP/

      I have tried and it works

      Reply
      • Mukesh Otwani says

        July 9, 2019 at 10:12 PM

        Hi Mali,

        I really appreciate your efforts for helping others…:)

        Reply
  13. uk says

    April 11, 2019 at 10:25 AM

    Hi mukesh,

    Tq,Very helpfull

    Reply
    • Mukesh Otwani says

      April 11, 2019 at 2:06 PM

      Hi Uk,

      You are most welcome…:)

      Reply
  14. pavithra says

    April 11, 2019 at 10:00 AM

    What does this error define

    [TestNG] Running:
    C:\Users\pavithra\AppData\Local\Temp\testng-eclipse-594331317\testng-customsuite.xml

    FAILED: verifyValidLogin
    java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases

    Reply
    • Mukesh Otwani says

      April 11, 2019 at 2:24 PM

      Hi Pavithra,

      This is line java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; which tells path of geckodriver path is not correct. Please refer this link too http://learn-automation.com/use-firefox-selenium-using-geckodriver-selenium-3/

      Reply
  15. pavithra says

    April 10, 2019 at 5:26 PM

    Kindly put geckodrive.exe file into your user folder then try it again(sometimes non admin user doesn’t gets proper privileges into Program Files folders) . Also check syntax and location of driver file is correct.

    Above as u replied me yesterday -I have save the gecko driver in User not in c driver

    Reply
    • Mukesh Otwani says

      April 10, 2019 at 7:29 PM

      Hi Pavithra,

      I don’t see any other error / exceptions apart from gecko driver file path issue. Because exception message itself mentions file path issue.

      Reply
  16. pavithra says

    April 10, 2019 at 11:33 AM

    Hi, I have tried the same as above but its shows error

    FAILED: verifyValidLogin
    java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases

    Reply
    • Mukesh Otwani says

      April 10, 2019 at 3:17 PM

      Hi Pavithra,

      Issue clearly corresponds to wrong gecko driver path (The path to the driver executable must be set by the webdriver.gecko.driver system property).

      Reply
  17. Abhay Kulshreshtha says

    February 19, 2017 at 4:19 PM

    Thanks Mukesh , Very helpful vedio.
    Significant contribution to Testing Community.

    Reply
    • Mukesh Otwani says

      February 20, 2017 at 6:41 AM

      Thanks..:)

      Reply
  18. Neelima says

    February 14, 2017 at 8:13 PM

    Hi Mukesh, my script has been implemented using data from excel, i too want refactor my code using POM, but facing issues, Is there any tutorial which can help me for this?,
    Else the above explanation is good enough for me when im not fetching my data from excel.
    Thanks,please do help me

    Reply
    • Mukesh Otwani says

      February 16, 2017 at 11:56 AM

      Hi Neelima,

      As per my understanding, you want to change your existing framework to Page Object Model, right?

      Reply
  19. shivani says

    February 10, 2017 at 5:29 AM

    Hi ,
    Nice tutorial. Was searching for something so clear since long 🙂

    Reply
    • Mukesh Otwani says

      February 10, 2017 at 7:10 PM

      Hi Shivani,

      I am happy to see that my blog post has helped you. Many many thanks for your appreciating comments.

      Reply
  20. jk says

    February 7, 2017 at 2:32 AM

    awesome!!! video with no parameters

    Reply
    • Mukesh Otwani says

      February 7, 2017 at 6:24 AM

      Thanks JK 🙂

      Reply
  21. Pooja says

    January 28, 2017 at 7:52 PM

    Hi Mukesh,

    If i need to pass data from excel sheet for the above framework.
    How do i go about it.

    Reply
    • Mukesh Otwani says

      January 30, 2017 at 9:33 AM

      Hi Pooja,

      Please refer this link http://learn-automation.com/read-and-write-excel-files-in-selenium/

      Reply
  22. Daisy G says

    January 21, 2017 at 6:55 PM

    Hi Mukesh, Nice tutorial.Is there a way to check if entire page has been loaded including all frames in page without using webdriverwait or implicit wait. If yes how.

    Reply
    • Mukesh Otwani says

      January 23, 2017 at 12:24 PM

      Hi Daisy,

      You can use javascript call for document.readyState to be equal to complete. But anyway implicit wait internally uses same.

      Reply
  23. nisha b says

    January 21, 2017 at 2:57 PM

    Hi Mukesh,
    Your comment is awaiting moderation.

    if i execute my selenium test whenever i found even one bug entire automation test had stopped . next test case does not get executed.
    so please tell after finding bug developer should fix the bug then only we excute test script or we just capture that bug and execute next script.
    if you try to say just capture the bug and eexcute next line script how we caputre the bug and execute next script

    Reply
    • Mukesh Otwani says

      January 21, 2017 at 8:59 PM

      Hi Nisha,

      In this case, you can put exception catch after every action. If you catches any exception which usually happens when bug comes out(as in your case) then after this next step of execution will proceed. You need to design your framework in a way so that each action goes through exception check.

      Reply
  24. kanchana says

    January 13, 2017 at 12:42 PM

    Hi mukesh ji, how can we automate homepage by using pagefactory, for ex:i need to count the no of socialicons in a given homepage?

    Reply
    • Mukesh Otwani says

      January 13, 2017 at 1:39 PM

      Hi Kanchana,

      First understand the fact that there is no relation between pagefactory and count of no. of socialicons. You can check no href properties or anchor links(depends on your application page) after navigating to corresponding controls. To get how to verify those links, please visit here http://learn-automation.com/find-broken-links-using-selenium/

      Reply
  25. Anusha says

    January 13, 2017 at 4:19 AM

    Hi Mukesh…Working on ur assignment .was just wondering how do i write text in paragraph…it does not work with send keys:(

    Reply
    • Mukesh Otwani says

      January 13, 2017 at 9:41 AM

      Hi Anusha,

      Are you using any web based editor tool like CK Editor? If not then please explain scenario.

      Reply
  26. Anusha says

    January 13, 2017 at 4:16 AM

    You are the best👍🏻👍🏻👍🏻sooper sooper sooper👌🏻👌🏻👌🏻

    Reply
    • Mukesh Otwani says

      January 13, 2017 at 9:42 AM

      Hi Anusha,

      Thanks Anusha…your positive comments are driving me forward.

      Reply
  27. John says

    January 10, 2017 at 12:36 PM

    Hi, your article is really helpful.

    I need to read the object from excel file.

    @FindBy(how=How.XPATH,using=”.//*[@id=’wp-submit’]”)

    here, I need to get “.//*[@id=’wp-submit’]” from excel file with page factory concept. Could you please suggest some ways to do it? I tried it. its throwing some error.

    Reply
    • Mukesh Otwani says

      January 10, 2017 at 1:53 PM

      Hi John,

      Please go through second section on this link http://learn-automation.com/read-and-write-excel-files-in-selenium/
      For an example, you can use it this way —>>> By Add_Button = By.xpath(object property from Excel);
      Add_Button is locator. Now you can use it as driver.findElement(AddButton).click();

      Reply
  28. Gaurav Khurana says

    December 7, 2016 at 11:37 AM

    THis is nice explanation but would be good if you can explain the with factory code. The first program is very much clear.

    But the POM with object factory has many new syntaxes. if you add a paragraph for that it would be good. Which one is more used in industry ?

    Reply
    • Mukesh Otwani says

      January 11, 2017 at 3:15 PM

      We use Page Object model with Page Factory it also helps in performance.

      Reply
  29. skay says

    November 30, 2016 at 4:34 PM

    public void login_wordpress(String uid,String pass)
    {
    username.sendKeys(uid);
    password.sendKeys(pass);
    submit_button.click();
    }

    Shouldn’t the above function be like this
    public void login_wordpress(String uid,String pass)
    {
    driver.findElement(username).sendKeys(uid);
    driver.findElement(password).sendKeys(pass);
    driver.findElement(submit_button).click();
    }

    Reply
    • Mukesh Otwani says

      November 30, 2016 at 4:50 PM

      Yes Skay I have to modified the code.. Thanks for update.

      Reply
  30. praneeth says

    November 27, 2016 at 7:44 PM

    Here it seems for every test case we are initializing and creating new object for driver. How to we maintain driver object as common for all pages and tests

    Reply
    • Mukesh Otwani says

      November 30, 2016 at 5:56 PM

      Hey Praneeth,

      You can check below video for this.

      Reply
  31. Sravan K Kumar says

    November 18, 2016 at 5:14 PM

    Dear Mukesh Otwani,
    iam creating “LoginPageNew ” like same as u ,
    and calling directly methods in another class.
    its showing null point Exception (but i am not create any “Page Factory” class)

    ” Ur class are very good ,iam following that ,
    i am not understand “Page Factory” class

    Reply
    • Mukesh Otwani says

      November 23, 2016 at 3:24 PM

      Hi Sravan,

      Make sure webdriver is passed in everypages then you wont find any null pointer exception.

      Reply
  32. nidhi says

    November 10, 2016 at 12:17 AM

    VERY WELL EXPLAINED. ALL SCRIPTS RAN WELL.
    THANK YOU SO MUCH

    Reply
    • Mukesh Otwani says

      December 14, 2016 at 12:28 AM

      HI Nidhi,

      Good to hear that. CHeers.

      Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Free Selenium Videos

https://www.youtube.com/watch?v=w_iPCT1ETO4

Search topic

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?

Stay connected via Facebook

Stay connected via Facebook

Archives

Footer

Categories

Recent Post

  • API Testing Using Postman And RestAssured
  • Disable Personalise Your Web Experience Microsoft Edge Prompt In Selenium
  • How To Fix Error: No tests found In Playwright
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Best and easy way to Group test cases in selenium

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?