Implementing the Page Object Model (Selenium + Python)


We are retiring this post in favor of a newer post: Page Object Model (Selenium, Python)
Please refer to the newer post. It has a more detailed architectural breakdown, provides many more code snippets and write an automated test for a very relatable application – Gmail. You could also visit our open-sourced Python + Selenium test automation framework based on the page object pattern and read through it’s wiki.

Problem: Testers think changing existing test scripts to use the page object model is complicated.

Why this post?

Tutorials on the page object model usually show you how to implement the page object model using a cliched login page as an example. Most online tutorials rarely show you how to modify your existing tests to use the page object model. This post is a follow up to our descriptive introduction to the page object model. In this tutorial, we provide a hands on example of how to revamp your existing test scripts to use the page object model.

A refresher

Within your web app’s UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place.[1]

The page object model allows us to do two things mainly:[2]
1) Encapsulate the low-level “internals” of the page – the ids of the buttons, classes of element, etc.
2) Make the client (of the Page Object) test methods more elegant by taking them to a higher level.

Test scenario

I am going to test the chess viewer widget on I am choosing to check if Black’s 21st move in the Casino Royale Chess Game is executed correctly. Black’s queen moves from the b6 square to the f2 square. We will verify that the b6 square is empty and that the f2 square has a black queen on it.
PS: Black’s 21st move in this game is the reason behind our company name Qxf2.


Implementing the page object model

For this tutorial, we will show the following:
1. Write a working test
2. Prepare to move to the page object model
3. Implement the page objects
4. Run the test
5. Compare with the first implementation

1. Write a working test
I am going to implement a working test. We will use this as a starting point. Let’s pretend that this is your existing test. I have written the following

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class qxf2move(unittest.TestCase):
    def setUp(self):
    def testUserMove21Black(self):
        self.assertIn("Mikhail Krasenkow vs Hikaru Nakamura (2007) \"Casino Royale\"",driver.title)
        #Click on Black's 21st move
        #Verify the squares b6 and f2 ([2,1], [6,5]) have the right pieces
        chess_square = driver.find_element_by_id("img_tcol5trow6")
        #Verify that the square f2 has a black queen (bq.png)
        chess_square = driver.find_element_by_id("img_tcol1trow2")
        #Verify that the square b6 is empty (clear.png)
    def tearDown(self):
if __name__=="__main__":

Here as you can see the test scripts contains the actual details of the attributes and ids as they appear in the page source. It is not easy to maintain these scripts in case of underlying changes. Hence we try to make the test script more readable and extendable by making a few changes.

2. Prepare to move to the page object model
– Identify the various objects and elements on the web page. Define them as objects and variables in the test script. E.g.: Title, Game_Id, Move_Str, Chess Board, Chess Piece, locators for the various objects


– Identify the various actions possible on these objects using the available elements. These actions can be defined as the methods in the test script. E.g.: get_Title, getCurrentBoard, create_mov_str, gotoMove, gotoStart, gotoEnd

3. Implement the different pages as page objects
-Separate the test case and the page objects, methods in different files. Here my test case is present in and the page objects, methods are present in

from selenium import webdriver
from import By
import unittest
import ChessGamePage
class TestChessGamePage(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
    def testUserMove21Black(self):
        "Test Black's 21st move (qxf2)"
        gameid = "1477101"
        player = "black"
        movenum = 21
        """List of the board position in the format (Piece,row,col)
        where top left corner of the board is row =0, col= 0,
        white player = 'w',black player = 'b'
        pawn(p), rook(r), knight(n), bishop(b), queen(q), and king(k)"""
        lst = [('br',0,4), ('bk',0,6),
               ('bn',1,3), ('bb',1,4), ('bp',1,5), ('bp',1,6), ('bp',1,7),
               ('bb',2,0), ('br',2,2), ('wb',2,5),
               ('wp',6,0), ('wn',6,3), ('bq',6,5), ('wb',6,6), ('wp',6,7),
               ('wr',7,1), ('wq',7,3), ('wr',7,4), ('wk',7,6)]
        chessgame_page = ChessGamePage.ChessGamePage(self.driver,gameid)
        page_title = chessgame_page.get_Title()
        self.assertIn("Mikhail Krasenkow vs Hikaru Nakamura (2007) \"Casino Royale\"", page_title)
        #Goto Black's 21st move 
        actualBoardb21 = chessgame_page.getCurrentBoard()
        expectedBoardb21 = ChessGamePage.ChessBoard()
        #Compare with the expected chess board
    def tearDown(self):
if __name__=="__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase (TestChessGamePage)

The above file does not contain the driver calls to get the elements in the page. For the sake of simplicity, we have not shown you how to implement a driver factory.

All the finer details are added to the files and as shown below

from selenium import webdriver
from import By
class Page(object):
    Base class that all page models can inherit from
    def __init__(self, selenium_driver, base_url=''):
        self.base_url = base_url
        self.driver = selenium_driver
        self.timeout = 30
    def find_element(self, *loc):
        return self.driver.find_element(*loc)
    def open(self,url):
        url = self.base_url + url

from selenium import webdriver
from import By
from Base_Page_Object import Page
class ChessGamePage(Page):
    move_str = ""
    url = ""
    """ Var0Mv(N*2-1) is the id for Nth white move
        Var0Mv(N*2)   is the id for Nth black move """
    id_str = "Var0Mv"
    startButton_loc = (By.ID, 'startButton')
    backbButton_loc = (By.ID, 'backButton')
    autoplayButton_loc = (By.ID, 'autoplayButton')
    forwardButton_loc = (By.ID, 'forwardButton')
    endButton_loc = (By.ID, 'endButton')
    def __init__(self, selenium_driver,gameid,base_url=''):
        Page.__init__(self, selenium_driver, base_url='') 
        self.url = 'perl/chessgame?gid=' + gameid
    # Actions
    def openpage(self):
    def get_Title(self):
        """Returns the page title"""        
        return self.driver.title
    def getCurrentBoard(self):
        """Returns the current chessboard positions"""
        board = ChessBoard(self.driver)
        return board
    def create_move_str(self,player,move):
        """Creates the value string using the player and move information"""
        if player.lower() == "white":
            self.move_str = self.id_str + str((move*2)-1)
            self.move_str = self.id_str + str(move*2)
    def goto_Move(self,player,move):
        """Clicks on the particular move"""
        move_loc = (By.ID,self.move_str)
    def goto_Start(self):
        """Clicks the start of the game button"""
    def goto_Back(self):
        """Clicks the ack one step bbutton"""
    def goto_AutoPlay(self):
        """Clicks the autoplay button"""
    def goto_Forward(self):
        """Clicks the one step forward button"""
    def goto_End(self):
        """Clicks the end of game button"""
"""This class represents the actual chess board present on the page"""
class ChessBoard(object):
    """This string is the id for the image(piece) present in each square(col,row) of the chess board"""
    id_str = "img_tcol%strow%s"
    def __init__(self,driver=None):
        self.driver = driver
        self.grid = []
    def loadFromPage(self):
        """Creates the chess matrix from the page data"""
        for row in xrange(8):
            for col in xrange(8):
                name = self.getSquare(row,col)
                if name:
                    piece = ChessPiece(name,row,col)
    def getSquare(self, row, col):
        """Returns the piece present at the particular row,col. None if the square is vacant"""
        elem = self.driver.find_element_by_id(self.id_str%(str(col),str(row)))
        src = elem.get_attribute('src')
        name = src.split("/")[-1].split(".")[0]
        return name if (name.lower() != 'clear') else None
    def populate(self,lst):
        """Creates the chess matrix as per the user data"""
        for entry in lst:
            name,row,col = entry
            piece = ChessPiece(name,row,col)
    def __str__(self):
        return str(self.grid)
    def __eq__(self,obj):
        return self.grid == obj.grid
"""This class represents the chessmen deployed on a chessboard for playing the game of chess"""
class ChessPiece(object):
    def __init__(self,name,row,col): = name
        self.row = row
        self.col = col
    def __eq__(self,obj):
        return ( == and self.row == obj.row and self.col == obj.col)
    def __hash__(self):
        tmp = 'row' + `self.row` + 'col' + `self.col` +
        return hash(tmp)
    def __str__(self):
        return "(%s,%d,%d)" % (, self.row, self.col)
    def __repr__(self):
        return "(%s,%d,%d)" % (, self.row, self.col)

4. Run the test
Here is the snapshot of the test run
run the page object model test

5. Compare with the first implementation
Let us compare the files and

You’ll notice that using the page object model, it becomes easy to add new testcases without bothering about the details of the page elements. Also any changes to the page elements do not change the testcases – only the logic in needs to be modified.



Subscribe to our weekly Newsletter

View a sample

9 thoughts on “Implementing the Page Object Model (Selenium + Python)

  1. Hi Vrushali Mahalley,

    Thank for your effort,

    I confuse at function __init__ on and, we will create constructor ‘selenium_driver’, but I see it’s not used on file test case because the test case file is using ‘setUP’ function calling Firefox instance. So, I think __init__ on files as above is useless – we can remove it

    If wrong, please correct for me

    1. Jame,
      Good question! To limit the tutorial to a reasonable length we chose to share the webdriver object with the Page Object and the Base Page Object through the test case .
      Here is the flow of execution
      def setUp(self):
      self.driver = webdriver.Firefox()
      Here the the instance of Firefox WebDriver is created which is then passed to the ChessGamePage object.
      chessgame_page = ChessGamePage.ChessGamePage(self.driver,gameid)
      class ChessGamePage(Page)
      ChessGamePage is derived from Page, hence __init__ in ChessGamePage in turn calls __init__ in Page class
      def __init__(self, selenium_driver,gameid,base_url=’’):
      Page.__init__(self, selenium_driver, base_url=’’)
      class Page(object):
      def __init__(self, selenium_driver, base_url=’’):
      self.base_url = base_url
      self.driver = selenium_driver
      For a more advanced and detailed architecture you can refer here:
      Hope this helps.

  2. Really very helpful. It would be really more helpful if you could provide any meterial to learn complete selenium with python(Using pytest framework). Hoping from you. Thank you!

  3. Hi Vrushali Toshniwal,
    I started to implement/understand your examples.
    If I have use ( from your examples) :
    chessgame_page = ChessGamePage.ChessGamePage(self.driver, gameid)
    I’ve got the error:
    TypeError: open() missing 1 required positional argument: ‘url’
    The error displayed on the console is correct because the open () method defined in the Page class needs the url reference to work.
    Perhaps you should use the openpage () method defined in the same ChessGamePage class
    def openpage (self): (self.url)
    so that it can reuse the open method of the Page class.

    the fix should be:
    chessgame_page = ChessGamePage.ChessGamePage(self.driver, gameid)

    What do you think?


Leave a Reply

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