1.实现Page Object
class BasePage:
"""
基础Page层,封装一些常用方法
"""
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)
from .basePage import BasePage
class BaiduPage(BasePage):
"""百度Page层, 百度页面封装操作到的元素"""
url = "http://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()
import unittest
from time import sleep
from selenium import webdriver
from .baidu_page import BaiduPage
class TestBaidu(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
def test_baidu_search_case(self):
page = BaiduPage(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)
2.poium测试库(简化了Page层元素的定义)
2.1 基本使用
from poium import Page, Element
class BaiduPage(Page):
""""百度Page层, 百度页面封装操作到的元素"""
search_input = Element(id_="kw")
search_button = Element(id_="su")
from .baidu_page import BaiduPage
import unittest
from selenium import webdriver
class TestBaidu(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
def test_baidu_search_case1(self):
page = BaiduPage(self.driver)
page.get("http://www.baidu.com")
page.search_input = "selenium"
page.search_button.click()
@classmethod
def tearDownClass(cls):
cls.driver.quit()
if __name__ == "__main__":
unittest.main(verbosity=2)
2.2 更多用法
# 支持8种定位方式
elem_id = Element(id_='id')
elem_name = Element(name='name')
elem_class = Element(class_name='class')
elem_tag = Element(tag='input')
elem_link_text = Element(link_text='link_text')
elem_partial_link_text = Element(partial_link_text='is_link')
elem_xpath = Element(xpath='//*[@id="kk]')
elem_css = Element(css='#id')
# 设置元素超时时间
search_input = Element(id_="kw", timeout=5)
search_button = Element(id_="su", timeout=30)
# 设置元素描述
username = Element(css='#loginAccount', describe="用户名")
password = Element(css='#loginPwd', describe="密码")
# 定位一组元素
search_result = Elements(xpath="//div/h3/a")