Page Object 1 百度搜索实例 (虫师《selenium3自动化测试实战--基于Python语言笔记40》)
作者:互联网
1.创建Page的基类(base.py)
import time 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)
2.百度搜索方法封装在一起(baidu_page.py)
from Page_Object.base import BasePage class BaiduPage(BasePage): """百度Page层,百度页面封装操作到的元素""" url = "https://www.baidu.com" def search_input(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()
3.百度搜索测试用例封装在一起(test_baidu.py)
import unittest from time import sleep from selenium import webdriver from Page_Object.baidu_page import BaiduPage class TestBaidu(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() def test_baidu_search_case1(self): page = BaiduPage(self.driver) page.open() page.search_input("selenium") page.search_button() sleep(2) self.assertEqual(page.get_title(), "selenium_百度搜索") def test_baidu_search_case2(self): page = BaiduPage(self.driver) page.open() page.search_input("unittest") page.search_button() sleep(2) self.assertEqual(page.get_title(), "unittest_百度搜索") def test_baidu_search_case3(self): page = BaiduPage(self.driver) page.open() page.search_input("page object") page.search_button() sleep(2) self.assertEqual(page.get_title(), "page object_百度搜索") @classmethod def tearDownClass(cls): cls.driver.quit() if __name__ == '__main': unittest.main(verbosity=2)
测试结果如下:
标签:search,虫师,name,Python,self,Object,driver,page,def 来源: https://www.cnblogs.com/kite123/p/11572813.html