Selenium的PageObject设计模式(2)

songerxing 2020-05-03

Selenium的PageObject设计模式(2)

一、代码与数据分离的方式(一)

1.excel做数据源时表格设计

Selenium的PageObject设计模式(2)

2.读取出excel文件内元素组装成数组形式返回

conf = ConfigUtils()
elements_path=conf.get_elements_url

class ElementExcelData:
    def __init__(self, sheet_name, element_path=elements_path):
        self.element_path = element_path
        # 打开excel文件
        self.workbook = xlrd.open_workbook(self.element_path)
        # sheet页名
        self.sheet = self.workbook.sheet_by_name(sheet_name)
        # 获取行数
        self.row_count = self.sheet.nrows

    def get_element_info(self):
        elements_info={}
        for i in range(1, self.row_count):
            element_info = {}
            element_info[‘element_name‘] = self.sheet.cell_value(i, 1)
            element_info[‘locator_type‘] = self.sheet.cell_value(i, 3)
            element_info[‘locator_value‘] = self.sheet.cell_value(i, 4)
            element_info[‘timeout‘] = int(self.sheet.cell_value(i, 5))
            elements_info[self.sheet.cell_value(i, 0)] = element_info
        return elements_info


def get_page_info(sheet_name):
    element_data = ElementExcelData(sheet_name)
    elements = element_data.get_element_info()
    return elements

3.读取excel为数据源

# 读取excel为数据源
elements = get_page_info(‘Login‘)

class LoginPage(BasePage):
    def __init__(self,driver):
        super().__init__(driver)

        # 方式三:
        self.username_inputbox = elements[‘username_inputbox‘]
        self.password_inputbox = elements[‘password_inputbox‘]
        self.login_button = elements[‘login_button‘]

二、代码与数据分离的方式(二)

1.yaml文件做数据源时.yml设计方式

Selenium的PageObject设计模式(2)

 2.读取出yaml文件内元素

conf = ConfigUtils()
elements_yaml_url=conf.get_elements_yaml_url

class ElementYamlData:
    def __init__(self, sheet_name, element_path=elements_yaml_url):
        self.sheet_name =sheet_name
        # 打开yaml文件
        self.file = open(element_path, ‘r‘, encoding=‘utf-8‘)
        # 读出yaml文件全部内容
        self.yaml_content = self.file.read()

    def read_yaml(self):
        yaml_list = yaml.load(self.yaml_content,Loader=yaml.FullLoader)
        elements = yaml_list[self.sheet_name]
        return elements

3.读取yaml文件为数据源

# 读取yaml文件为数据源
element_infos = ElementYamlData(‘LoginPage‘)
elements=element_infos.read_yaml()

class LoginPage(BasePage):
    def __init__(self,driver):
        super().__init__(driver)

        # 方式三:
        self.username_inputbox = elements[‘username_inputbox‘]
        self.password_inputbox = elements[‘password_inputbox‘]
        self.login_button = elements[‘login_button‘]

相关推荐