Python+Selenium PO模式Web自动化测试实战

1、项目结构

Python+Selenium PO模式Web自动化测试实战_第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():
    #     # 获取文件

你可能感兴趣的:(selenium,自动化,测试工具)