poium测试库实现page_object模式
page_object模式实现
selenium中page object模式下的实现
定义一个基础类
import time
from time import sleep
class BasePage:
# 基础pagen层,封装一些常用方法。
def __init__(self, driver):
self.driver = driver
# 打开页面
def open(self, url=None):
if url is None:
self.driver.get(self.url)
else:
self.driver.get(url)
# id 定位
def by_id(self, id_):
return self.driver.find_element_by_id(id_)
# name 定位
def by_name(self, name):
return self.driver.find_element_by_name(name)
# class 定位
def by_class(self, class_name):
return self.driver.find_element_by_class_name(class_name)
# xpath 定位
def by_xpath(self, xpath):
return self.driver.find_element_by_xpath(xpath)
# css 定位
def by_css(self, css):
return self.driver.find_element_by_css_selector(css)
# 获取title
def get_title(self):
return self.driver.title
# 获取页面text,仅使用xpath定位
def get_text(self, xpath):
return self.by_xpath(xpath).text
# 执行JavaScript脚本
def js(self, script):
self.driver.execute_script(script)
# 封装休眠时间
def sleep(self, sec):
time.sleep(sec)
操作元素类
from selen import BasePage
from selenium import webdriver
class BD(BasePage):
"""百度Page层,百度页面封装操作到的元素"""
url = "https://www.baidu.com"
def search_input(self, search_key):
self.by_id("kw").send_keys(search_key)
def search_button(self):
self.by_id("su").click()
unittest框架实现
import unittest
from time import sleep
from selenium import webdriver
from bd import BD
from selen import BasePage
class TestBaidu(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
def test_baidu_search_case1(self):
page = BD(self.driver)
page.open()
page.search_input("selenium")
page.search_button()
sleep(2)
self.assertEqual(page.get_title(), "selenium_百度搜索")
@classmethod
def tearDownClass(cls):
cls.driver.quit()
if __name__ == '__main__':
unittest.main(verbosity=2)
通过poium测试库实现page_object模式的简单程序
from poium import Page,NewPageElement
import unittest
from selenium import webdriver
from time import sleep
class BaiduPage(Page):
"""百度Page 层,百度页面封装操作到的元素"""
search_input = NewPageElement(id_="kw")
search_button = NewPageElement(id_="su")
class TestBaidu(unittest.TestCase):
def test_baidu_search_case1(self):
self.driver = webdriver.Chrome()
page = BaiduPage(self.driver)
page.get("https://www.baidu.com")
page.search_input = "selenium"
page.search_button.click()
sleep(5)
self.driver.quit()
if __name__ =='__main__':
unittest.main()
poium测试库更多用法
1.poium 支持 8 种定位方式
elem_id = NewPageElement(id_=‘id’)
elem_name = NewPageElement(name=‘name’)
elem_class = NewPageElement(class_name=‘class’)
elem_tag = NewPageElement(tag=‘input’)
elem_link_text = NewPageElement(link_text=‘this_is_link’)
elem_partial_link_text = NewPageElement(partial_link_text=‘is_link’)
elem_xpath = NewPageElement(xpath=’//*[@id=“kk”]’)
elem_css = NewPageElement(css=’#id’)
2.设置元素超时时间 timeout
elem_id = NewPageElement(id_=‘id’,timeout=5)
3.设置元素描述 describe 参数
elem_id = NewPageElement(id_=‘id’,describe=‘yonghuid’)
4.定位一组元素
search_result = NewPageElements(xpath="//div/h3/a")