1、项目结构
2、BASE层封装代码
# -- coding: UTF-8 --
import datetime
import os
from selenium.webdriver.support.select import Select
class BasePage:
# 构造函数,初始化方法
def __init__(self, driver):
self.driver = driver
self.driver.maximize_window()
self.driver.implicitly_wait(5)
# 获取URL
def geturl(self):
self.driver.get(self.url)
# 定位元素
def locator_element(self, loc):
return self.driver.find_element(*loc)
def locator_elements(self, loc):
return self.driver.find_elements(*loc)
def get_text(self, loc):
return self.locator_element(loc).text
# 重构send_keys方法
def send_keys(self, loc, value):
self.locator_element(loc).send_keys(value)
# self.driver.find_element(*loc).send_keys(value)
def clear(self, loc):
self.locator_element(loc).clear()
# 重构下拉框操作
def select(self, loc, value):
sel = Select(self.locator_element(loc))
sel.select_by_visible_text(value)
# 重构click方法
def click(self, loc):
self.locator_element(loc).click()
# frame切换
def switch_to_frame(self, frame):
self.driver.switch_to.frame(frame)
# frame切换返回
def switch_to_default_content(self):
self.driver.switch_to.default_content()
# 切换窗口
def switch_to_window(self, title):
for handle in self.driver.window_handles:
self.driver.switch_to.window(handle)
if title == self.driver.title:
break
# 截屏,默认在项目目录下生成图片
def save_screenshot(self, filename):
self.driver.save_screenshot(filename)
# 截屏,可以指定文件路径
def get_screenshot_as_file(self, filename):
pro_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) # 获取当前项目的根路径
screenshot_dir = os.path.join(pro_dir, "screenshot") # 根路径下创建文件夹screenshot
if not os.path.exists(screenshot_dir):
os.makedirs(screenshot_dir)
data_file = datetime.datetime.now().strftime('%Y%m%d') # 当日日期
screenshot_today_dir = os.path.join(screenshot_dir, data_file) # 当前日期文件夹
if not os.path.exists(screenshot_today_dir):
os.mkdir(screenshot_today_dir) # 不存在则创建日期文件夹
now_time = datetime.datetime.now().strftime('%H%M%S') # 时间戳%H%M%S%f
filename = f'{filename}_{now_time}.png' # 拼接文件名 时间戳+文件名+.png
filepath = os.path.join(screenshot_today_dir, filename)
self.driver.get_screenshot_as_file(filepath)
def quit(self):
self.driver.quit()
3、Excel文件读写封装
# -- coding: UTF-8 --
import datetime
import openpyxl
class OperateExcel:
# @staticmethod
# def get_object_path():
# # 获取文件的绝对路径,相对路径容易出错
# path = os.path.abspath(os.path.dirname(__file__)).split('/base')[0]
# filepath = f'{path}/data/goods_search.xlsx'
# return filepath
@staticmethod
def read_excel(excel_path, sheet_name):
wb = openpyxl.load_workbook(excel_path)
sheet = wb[sheet_name]
rows = sheet.max_row
cols = sheet.max_column
data_list = []
for row in range(2, rows + 1):
temp_data = []
for col in range(1, cols + 1):
value = sheet.cell(row=row, column=col).value
temp_data.append(value)
data_list.append(tuple(temp_data))
print(data_list)
return data_list
@staticmethod
def write_excel(excel_path, sheet_name, row, col, value):
# current_time = datetime.datetime.now()
wb = openpyxl.load_workbook(excel_path)
sheet = wb[sheet_name]
sheet.cell(row, col, value)
wb.save(excel_path)
4、测试案例代码
# -- coding: UTF-8 --
import datetime
import os
import pytest
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from base.operate_excel import OperateExcel
from po.aptitude_pic_page import AptitudePicPage
from po.goods_search_page import GoodSearchPage
from po.index_login_page import IndexLoginPage
from po.index_logout_page import IndexLogoutPage
class TestCase:
# 1.实例化一个ChromeOptions对象
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 2.将ChromeOptions实例化的对象option作为参数传给Chrome对象,规避部分网站的检测识别
driver = webdriver.Chrome(executable_path='chromedriver', options=option)
@staticmethod
def get_object_path():
# 获取文件的绝对路径,相对路径容易出错
path = os.path.abspath(os.path.dirname(__file__)).split('/case')[0]
filepath = f'{path}/data/goods_search.xlsx'
return filepath
# 打开浏览器并登录
def setup_class(self):
IndexLoginPage(self.driver).login()
# 退出浏览器
def teardown_class(self):
IndexLogoutPage(self.driver).logout()
# 用例1,实现登录后查询多种商品,查询结果写入Excel文件中
@pytest.mark.parametrize('args', OperateExcel().read_excel(get_object_path(), '搜索'))
# @pytest.mark.skip(reason='调试跳过')
def test_case_001(self, args):
n = args[0] # 根据序号定位excel中的位置
value = GoodSearchPage(self.driver).goods_search(args[1])
OperateExcel().write_excel(TestCase().get_object_path(), '搜索', n+1, 3, value)
OperateExcel().write_excel(TestCase().get_object_path(), '搜索', n+1, 4, datetime.datetime.now())
5、data文件夹中的测试数据(黄色部分内容为写入数据)
*序号搜索关键字*商品信息(原价最高)**搜索日期1电视小米透明OLED电视 55英寸 黑色
49999元2022-06-04 0:32:072风扇米家空调 清凉版 大1匹
1699元 1999元2022-06-04 0:32:123黑鲨5黑鲨4S Pro 16GB+512GB
3599元 5499元2022-06-04 0:32:164手机Xiaomi MIX Alpha
19999元2022-06-04 0:32:225红米Redmi MAX 100" 巨屏电视 枪色
19999元2022-06-04 0:32:286牙刷T700+2支全效超薄型(热销爆款-1年量)
359元2022-06-04 0:32:337耳机Redmi K50 Pro 12GB+512GB&Buds 4 Pro(镜湖白)套装
4398元2022-06-04 0:32:398净化器米家循环风空气净化器 白色
2199元 2499元2022-06-04 0:32:449加湿器米家纯净式智能加湿器 Pro 白色
899元2022-06-04 0:32:4810电吹风米家高速吹风机 H900 深空锖
999元 1299元2022-06-04 0:32:53
6、po层登录模块
# -- coding: UTF-8 --
import time
from selenium.webdriver.common.by import By
from base.base_pae import BasePage
class IndexLoginPage(BasePage):
# 主页地址
url = r"https://www.mi.com/index.html"
# 页面元素定位
login_loc = (By.XPATH, '//*[@id="J_siteUserInfo"]/a[1]')
protocol = (By.XPATH, '//*[@id="stat_e3c9df7196008778"]/div[2]/div[2]/div/div/div/div[3]/button[1]')
username = (By.XPATH, '//*[@id="rc-tabs-0-panel-login"]/form/div[1]/div[1]/div[2]/div/div/div/div/input')
password = (By.XPATH, '//*[@id="rc-tabs-0-panel-login"]/form/div[1]/div[2]/div/div[1]/div/input')
check_box = (By.XPATH, '//*[@id="rc-tabs-0-panel-login"]/form/div[1]/div[3]/label/span[1]/input')
sumit = (By.XPATH, '//*[@id="rc-tabs-0-panel-login"]/form/div[1]/button')
# 页面业务流操作(登录)
def login(self, user='******', psw='******'):
self.geturl()
self.click(self.login_loc)
time.sleep(2)
# 判断用户协议是否存在,如果存在点击同意
protocol = self.locator_elements(self.protocol)
if protocol:
self.click(self.protocol)
self.send_keys(self.username, user)
self.send_keys(self.password, psw)
self.click(self.check_box)
self.click(self.sumit)
7、po层退出模块
# -- coding: UTF-8 --
import time
from selenium.webdriver.common.by import By
from base.base_pae import BasePage
class IndexLogoutPage(BasePage):
# 页面元素定位
login_loc = (By.XPATH, '//*[@id="J_siteUserInfo"]/a[1]')
logout_loc = (By.XPATH, '//*[@id="J_userLogout"]')
# 页面业务流操作(退出登录)
def logout(self):
# 判断是否存在登录,如果存在说明处于无用户登录状态,直接关闭浏览器,如果不存在,说明为用户登录状态,点击退出登录
login = self.locator_element(self.login_loc)
if not login:
self.click(self.logout_loc)
time.sleep(3)
self.quit()
8、po查询案例模块
# -- coding: UTF-8 --
import time
from selenium.webdriver.common.by import By
from base.base_pae import BasePage
class GoodSearchPage(BasePage):
# 页面元素定位
search_loc = (By.ID, 'search') # 搜索框
search_summit = (By.XPATH, '//*[@id="J_submitBtn"]/input') # 搜索按钮
order = (By.XPATH, '//*[@id="app"]/div[2]/div/div/div[2]/div[3]/div/div[1]/ul[1]/li[4]/a') # 商品列表排序按钮
max_price = (By.XPATH, '//*[@id="app"]/div[2]/div/div/div[2]/div[3]/div/div[2]/div[1]/div[1]') # 第一位置商品
index_xiaomi = (By.LINK_TEXT, '小米商城') # 返回小米商城首页
# 页面操作(登录后搜索指定商品,并取出对应的价格最高商品)
def goods_search(self, value):
self.clear(self.search_loc)
self.send_keys(self.search_loc, value)
self.click(self.search_summit)
# 对查询结果进行按价格排序后取处理
self.click(self.order)
self.click(self.order)
time.sleep(2)
if self.locator_element(self.max_price): # 如果查询结果存在,则获取商品信息
num = self.get_text(self.max_price)
return num
版权归原作者 Buaixiao 所有, 如有侵权,请联系我们删除。