通常是三類文件
1、定位:把所有元素的定位寫在這(屬性)徙邻,如果系統(tǒng)大排嫌,可以按功能模塊寫在不同的文件夾中
locators.py
# 頁面中有二類:一類是元素,元素的定位缰犁,一類是元素的方法
from selenium.webdriver.common.by import By
# 一個大的功能模塊寫在一個文件中
class MainPageLocators(object):
search_text = (By.ID, "sb_form_q")
click_search = (By.ID, "sb_form_go")
class SearchResultPageLocators(object):
search_result = (By.ID, "b_results")
2淳地、操作方法:把頁面所有的動作寫成方法(方法)怖糊,每個方法封裝,等待颇象,清除和操作等
pages.py
# 與定位的類名匹配
# 公共的方法提取出來
from .locators import MainPageLocators,SearchResultPageLocators
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class BasePage(object):
def __init__(self,driver):
self.driver=driver
def save_pic(self, filepath):
self.driver.get_screenshot_as_file(filepath)
class MainPage(BasePage):
def enter_search_text(self, text):
# lambda是匿名函數(shù) *是傳參的格式是元組類型需要解包
WebDriverWait(self.driver, 10).until(
lambda driver: driver.find_element(*MainPageLocators.search_text)
)
element = self.driver.find_element(*MainPageLocators.search_text)
element.clear()
element.send_keys(text)
def click_search_button(self):
element = self.driver.find_element(*MainPageLocators.click_search)
element.click()
def title_matches(self):
return self.driver.title
class SearchResultPage(BasePage):
def results_found(self):
# 等待元素加載出來后返回元素文本信息
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(SearchResultPageLocators.search_result))
print(self.driver.find_element(*SearchResultPageLocators.search_result).text)
return self.driver.find_element(*SearchResultPageLocators.search_result).text
3伍伤、測試用例:
使用測試管理執(zhí)行框架:可以是unittest或pytest都可以
from selenium import webdriver
import time
import unittest
import datetime,os
from ..pages import pages
class TestBingSo(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("這是初始化開始測試")
parent_abspath = os.path.abspath(os.path.dirname(os.getcwd()))
driver_path =os.path.join(parent_abspath,"driver/chromedriver")
cls.driver = webdriver.Chrome(executable_path=driver_path)
cls.driver.get("https://cn.bing.com/?ensearch=1&FORM=BEHPTB")
cls.driver.maximize_window()
@classmethod
def tearDownClass(cls):
print("執(zhí)行完成環(huán)境銷毀")
cls.driver.quit()
def test_soso(self):
main_page =pages.MainPage(self.driver)
assert 'Bing' in main_page.title_matches()
main_page.enter_search_text("python")
main_page.click_search_button()
search_result_page = pages.SearchResultPage(self.driver)
assert 'Python' in search_result_page.results_found()
search_result_page.save_pic(str(datetime.datetime.now())+"_soso.png")
if __name__ == '__main__':
unittest.main()