PO设计模式的思想是:页面元素定位与操作分开;

一般把查找元素的操作放在BasePage文件中,对元素进行操作的代码放在具体的case文件中;

一、先定义badidu_page.py文件

代码如下:

class BasePage():
    def find_id(self,id_key):
        self.driver.find_element_by_id(id_key)
    def find_name(self,name_key):
        self.driver.find_element_by_name(name_key)

class BaiduPage(BasePage):
    def __init__(self, driver):
        self.driver = driver
    def open(self, url):
        self.driver.get(url)
    def search_box(self, search_key):

        self.driver.find_element_by_id("kw").send_keys(search_key)
    def search_button(self):
        self.driver.find_element_by_id("su").click()

二、调用badidu_page.py文件,并使用unittest编写用例

from selenium import webdriver
from baidu_page import BaiduPage
import unittest

class BaiduTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls) :#初始定义,setUpClass只需启动一次浏览器即可
        cls.driver = webdriver.Chrome()
        cls.url = "https://www.baidu.com"
    @classmethod
    def tearDownClass(cls)  :
        cls.driver.quit()
    def test_case_01(self):
        page = BaiduPage(self.driver)#实例化badidu_page.py文件中的BaiduPage类
        page.open(self.url)#调用BaiduPage类下的open方法,进行传参url地址
        page.search_box("selenium")#调用BaiduPage类下的search_box方法进行传参搜索内容
        page.search_button()#调用BaiduPage尖下的search_button方法
        self.r = "01成功"
    def test_case_02(self):
        page = BaiduPage(self.driver)
        page.open(self.url)
        page.search_box("python")
        page.search_button()
        self.r = "02成功"

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