Python+Selenium uses Page Object to automate page testing

Page Object mode is a test design mode in Selenium. It mainly designs each page as a Class, which contains the elements (buttons, input boxes, headers, etc.) that need to be tested in the page. In the Selenium test page, page elements can be obtained by calling page classes, which cleverly avoids changing the test page code when the page element id or location changes. When the page element id changes, you only need to change the properties of the page in the test page Class.

The Page Object pattern is an automated test design pattern that separates page positioning from business operations, separates test objects (element objects) from test scripts (use case scripts), and improves the maintainability of use cases.

unittest is a unit test framework for designing a wide variety of test cases. PageObject-designed page classes (objects) can be invoked to design more maintainable use cases. It provides case organization and execution, provides rich comparison (assertion) methods, provides rich logs, and is uniformly applicable to the development and execution of web automation use cases.

Design ideas using PO mode are as follows:

1. Define the page base class to encapsulate the methods common to all pages.

# coding=utf-8
Created on 2016-8-13
@author: Jennifer
Project:Base Class BasePage,The way to encapsulate all pages in common,
Definition open Function, redefine find_element,switch_frame,send_keys Equal function.
Define the driver in the initialization method driver,basic url,title
WebDriverWait Explicit wait mode is provided.
from import WebDriverWait
from import expected_conditions as EC

class BasePage(object):
    BasePage Method of encapsulating all pages in common, for example driver, url ,FindElement etc.
    #Initialize driver, url, pagetitle, etc.
    #When instantiating a BasePage class, the first thing you do is u init_u Method, the input of this method is actually the input of BasePage class.
    #_u init_u Method cannot have a return value, it can only return None
    #self is only the instance itself, as opposed to the class Page.
    def __init__(self, selenium_driver, base_url, pagetitle):
        self.driver = selenium_driver
        self.base_url = base_url
        self.pagetitle = pagetitle
    #Assert that the page entered is correct by title.
    #Use title to get the current window title, check if the input title is in the current title, and return the comparison result (True or False)
    def on_page(self, pagetitle):
        return pagetitle in self.driver.title
    #Open the page and verify that the page links are loaded correctly
    #With single underline_ The starting method, when using import *, is not imported, guaranteeing that the method is class private.
    def _open(self, url, pagetitle):
        #Open access link address with get
        #Use assert to verify whether the open window title matches the configured title. Call on_page() method
        assert self.on_page(pagetitle), u"Failed to open page %s"%url
    #Define open method, call _ open() to open the link
    def open(self):
        self._open(self.base_url, self.pagetitle)
    #Override Element Location Method
    def find_element(self,*loc):
#        return self.driver.find_element(*loc)
            #Ensure that elements are visible.
            #Note: The following elements, which are tuples, need to be added*. Python has this feature of putting arguments in tuples.
#            WebDriverWait(self.driver,10).until(lambda driver: driver.find_element(*loc).is_displayed())
            #Note: The following arguments are tuples themselves and do not need to be added*
            return self.driver.find_element(*loc)
            print u"%s Not found on page %s element"%(self, loc)
    #Override switch_frame method
    def switch_frame(self, loc):
        return self.driver.switch_to_frame(loc)
    #Define script methods to execute js scripts, scopes to execute results
    def script(self, src):
    #Rewrite Definition send_keys method
    def send_keys(self, loc, vaule, clear_first=True, click_first=True):
            loc = getattr(self,"_%s"% loc)  #getattr is equivalent to implementing self.loc
            if click_first:
            if clear_first:
        except AttributeError:
            print u"%s Not found on page %s element"%(self, loc)

2. Define the basic operation of the login page.

All page element positioning is defined at this level, and once the UI is changed, it is only necessary to modify the properties of the page object at this level.

# coding=utf-8
Created on 2016-8-13
@author: Jennifer
Project:Basic page operation methods: open,input_username,input_password,click_submit
from import By
from test_8_3_2_BasePage import BasePage

#Inherit BasePage Class
class LoginPage(BasePage):
    #Locator, locating element objects through element attributes
    username_loc =(By.NAME,'email')
    password_loc =(By.NAME,'password')
    submit_loc =(By.ID,'dologin')
    span_loc =(By.CSS_SELECTOR,"div.error-tt>p")
    dynpw_loc =(By.ID,"lbDynPw")
    userid_loc =(By.ID,"spnUid")
    #Overriding methods by inheritance: If the method names of the subclass and the parent are the same, the subclass's own method is preferred.
    #Open Web Page
    def open(self):
    #Call _in page open Open Connection
        self._open(self.base_url, self.pagetitle)
    #Enter user name: call send_keys object, enter user name
    def input_username(self, username):
#        self.find_element(*self.username_loc).clear()
    #Enter password: call send_keys object, enter password
    def input_password(self, password):
#        self.find_element(*self.password_loc).clear()
    #Click Login: Call send_keys object, click login
    def click_submit(self):
    #Unreasonable username or password is Tip box content display
    def show_span(self):
        return self.find_element(*self.span_loc).text
    #Switch login mode to dynamic password login (valid under IE)
    def swich_DynPw(self):
    #User ID lookup in logon success page
    def show_userid(self):
        return self.find_element(*self.userid_loc).text

3. Use the unittest framework to write test cases

# coding=utf-8
Created on 2016-8-13
@author: Jennifer
Project:Use unittest The framework writes test cases.
import unittest 
from test_8_3_2_LoginPage import LoginPage
from selenium import webdriver

class Caselogin126mail(unittest.TestCase):
          Logged in to mailbox 126 case
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.url =""
        self.username ="XXX"
        self.password ="XXX"
    #Use Case Executors
    def test_login_mail(self):
        #Declare LoginPage class objects
        login_page = LoginPage(self.driver, self.url, u"NetEase")
        #Invoke Open Page Component
        #Switch to Logon Frame
        #Invoke User Name Input Component
        #Invoke Password Input Component
        #Invoke Click Login Button Component

    def tearDown(self):
if __name__ == "__main__":

Finally: Welcome to the summary of Python Automation Test Engineer's Core Knowledge Points, which is a 300-page pdf document collected by Editor! Software Testing Technology Exchange Group: (1127563538) These materials are the knowledge points that interviewers must ask during the interview. The chapter includes a lot of knowledge points, including basic knowledge, Linux prerequisites, Shell, Internet program principles, Mysql database, package tool topics, interface testing tools, test advanced-Python programming, Web automation testing, APP automation testing, interface automation testing, interface automation testing, etc. Testing Advanced Continuous Integration, Test Architecture Development Test Framework, Performance Testing, Security Testing, etc.

Tags: Python Java Javascript software testing Testing

Posted by stef686 on Tue, 17 May 2022 19:14:09 +0300