Selenium - WebDriver: Page Objects

This chapter is a tutorial introduction to page objects design pattern. A page object represents an area in the web application user interface that your test is interacting.

Benefits of using page object pattern:

  • Creating reusable code that can be shared across multiple test cases
  • Reducing the amount of duplicated code
  • If the user interface changes, the fix needs changes in only one place

1. Test case

Here is a test case which searches for a word in python.org website and ensure some results are found.

import unittest
from selenium import webdriver
import page

class PythonOrgSearch(unittest.TestCase):
    """A sample test class to show how page object works"""

    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get("http://www.python.org")

    def test_search_in_python_org(self):
        """
        Tests python.org search feature. Searches for the word "pycon" then verified that some results show up.
        Note that it does not look for any particular text in search results page. This test verifies that
        the results were not empty.
        """

        #Load the main page. In this case the home page of Python.org.
        main_page = page.MainPage(self.driver)
        #Checks if the word "Python" is in title
        assert main_page.is_title_matches(), "python.org title doesn‘t match."
        #Sets the text of search textbox to "pycon"
        main_page.search_text_element = "pycon"
        main_page.click_go_button()
        search_results_page = page.SearchResultsPage(self.driver)
        #Verifies that the results page is not empty
            assert search_results_page.is_results_found(), "No results found."

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

2. Page object classes

The page object pattern intends creating an object for each web page. By following this technique a layer of separation between the test code and technical implementation is created.

The page.py will look like this:

from element import BasePageElement
from locators import MainPageLocators

class SearchTextElement(BasePageElement):
    """This class gets the search text from the specified locator"""

    #The locator for search box where search string is entered
    locator = ‘q‘

class BasePage(object):
    """Base class to initialize the base page that will be called from all pages"""

    def __init__(self, driver):
        self.driver = driver

class MainPage(BasePage):
    """Home page action methods come here. I.e. Python.org"""

    #Declares a variable that will contain the retrieved text
    search_text_element = SearchTextElement()

    def is_title_matches(self):
        """Verifies that the hardcoded text "Python" appears in page title"""
        return "Python" in self.driver.title

    def click_go_button(self):
        """Triggers the search"""
        element = self.driver.find_element(*MainPageLocators.GO_BUTTON)
        element.click()

class SearchResultsPage(BasePage):
    """Search results page action methods come here"""

    def is_results_found(self):
        # Probably should search for this text in the specific page
        # element, but as for now it works fine
        return "No results found." not in self.driver.page_source

3. Page elements

The element.py will look like this:

from selenium.webdriver.support.ui import WebDriverWait

class BasePageElement(object):
    """Base page class that is initialized on every page object class."""

    def __set__(self, obj, value):
        """Sets the text to the value supplied"""
        driver = obj.driver
        WebDriverWait(driver, 100).until(
            lambda driver: driver.find_element_by_name(self.locator))
        driver.find_element_by_name(self.locator).send_keys(value)

    def __get__(self, obj, owner):
        """Gets the text of the specified object"""
        driver = obj.driver
        WebDriverWait(driver, 100).until(
            lambda driver: driver.find_element_by_name(self.locator))
        element = driver.find_element_by_name(self.locator)
        return element.get_attribute("value")

4. Locators

One of the practices is to separate the locator strings from the place where they are being used. In this example, locators of the same page belong to same class.

The locators.py will look like this:

from selenium.webdriver.common.by import By

class MainPageLocators(object):
    """A class for main page locators. All main page locators should come here"""
    GO_BUTTON = (By.ID, ‘submit‘)

class SearchResultsPageLocators(object):
    """A class for search results locators. All search results locators should come here"""
    pass
时间: 2024-10-11 16:25:01

Selenium - WebDriver: Page Objects的相关文章

Selenium关于Page Objects

介绍页面对象设计模式.一个页面对象表示在你测试的web页面用户交互的界面. 使用页面对象模式的有点: 创建可重用的代码可以在多个测试用例中使用 减少重复的代码量 如果用户界面改变,只需要修改一个地方   1.Test case 下面的测试用例是在百度中搜索关键字,并返回相应的结果 import unittest from selenium import webdriver import page class BaiduSearch(uinttest.TestCase): def setUp(se

selenium+Page Objects(第三话)

写好BasePage基类和页面元素定位后,就可以针对每个页面写业务逻辑了 1.编写每个页面page类,拿其中一个页面为例 fourth_page.py(名字我随便取的,实际中希望能取一些有意义的名字) # coding: utf-8 # author: hmk from pages.BasePage import BasePage from locators.locators import Locators class FourthPage(BasePage): """定义一

Page Object Model | POM (Selenium Webdriver For Python)

研究Selenium + python 自动化测试有近两个月了,不能说非常熟练,起码对selenium自动化的执行有了深入的认识. 从最初无结构的代码,到类的使用,方法封装,从原始函数调用,到重定义函数.从变量驱动,到数据驱动,再到关键字驱动,一步一步的默默走向自动化框架的构建.虽然还有没有投入使用,只是写几个demo,就慢慢的发现了 selenium自动用例脚本,相似功能地方,代码基本都是一样的,界面元素换个查找方式,把原来的使用 xpath方式,改为使用 id 查找,需要对每个用例脚本都要改

Selenium WebDriver 之 PageObjects 模式 by Example

目录 1. 项目配置 2. 一个WebDriver简单例子 3. 使用Page Objects模式 4. 总结 5. Troubleshooting 6. 参考文档 本篇文章通过例子来阐述一下Selenium2.0 WebDriver 之 Page Objects模式. 项目配置 maven 3, pom.xml配置如下 <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>s

浅析selenium的page object模式

selenium目前比较流行的设计模式就是page object,那么到底什么是page object呢,简单来说,就是把页面作为对象,在使用中传递页面对象,来使用页面对象中相应的成员或者方法,能更好的提现java的面向对象和封装特性,首先看一下官网的解释: Page Object Design Pattern Page Object is a Design Pattern which has become popular in test automation for enhancing tes

Selenium Webdriver——处理Table

html table是由 table 元素以及一个或多个 tr.th 或 td 元素组成.如下: HTML源码如下: <html> <head> <meta http-equiv="Content-Language" content="zh-cn"> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"&

Selenium WebDriver 处理table

首先,html table是由 table 元素以及一个或多个 tr.th 或 td 元素组成. for example: 这是一个简单的html table: 源码如下: <html><head><meta http-equiv="Content-Language" content="zh-cn"><meta http-equiv="Content-Type" content="text/ht

Selenium自动化Page模式(Python)

Selenium是当前主流的web自动化工具,提供了多种浏览器的支持(Chrome,Firefox, IE等等),当然大家也可以用自己喜欢的语言(Java,C#,Python等)来写用例,很容易上手.当大家写完第一个自动化用例的时候肯定感觉”哇...好牛x“,但是大家用余光扫了一下代码后,内心也许是崩溃的,因为太乱了!像这样: __author__ = 'xua' from selenium import webdriver from selenium.webdriver.common.keys

解决Ruby在IE11中报Unable to get browser (Selenium::WebDriver::Error::NoSuchWindowError)的错误

转载地址:http://www.tuicool.com/articles/BRnqeu2 I was updating the browser WebDrivers for    Seleno    when I hit an issue with the InternetExplorerDriver. I was running Selenium WebDriver 2.43.1 on Windows 8.1 and using Internet Explorer 11. The test w