Playwright的封装

📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)

📝 职场经验干货:

软件测试工程师简历上如何编写个人信息(一周8个面试)

软件测试工程师简历上如何编写专业技能(一周8个面试)

软件测试工程师简历上如何编写项目经验(一周8个面试)

软件测试工程师简历上如何编写个人荣誉(一周8个面试)

软件测试行情分享(这些都不了解就别贸然冲了.)

软件测试面试重点,搞清楚这些轻松拿到年薪30W+

软件测试面试刷题小程序免费使用(永久使用)


Playwright与selenium都是基于WEB的GUI自动化测试的框架,前面我介绍了selenium的封装,这里来介绍基于Playwright的封装。

1.目录结构

首先仍旧先来介绍目录结构

____________________________________________________________
|______basepage			基础操作目录
|___________base.py			封装基本操作
|___________db.py			封装数据库操作
|___________page.py			封装Playwright page对象
|______data				测试数据目录
|___________data.yaml			数据
|___________data.py			封装对data.yaml数据的获取操作
|______pageobject			页面封装和业务封装目录
|___________flowobject.py		封装业务操作
|___________pageobject.py		封装页面操作
|______test				测试目录
|___________test.py			封装测试

2. 基础操作(basepage)

basepage目录封装基础操作,包括base.py、db.py和page.py

2.1 base.py

base.py对Playwright专门做了调整,包括base、judge、WaitUtils和异常四个类。分别封装寻找元素、断言和等待方法。

2.1.1 base类

代码如下​​​​​​​

class base:
    @staticmethod
    #通过label查找元素
    def find_element_by_label(page,label_str):
        return page.get_by_label(label_str)
    @staticmethod
    #通过text查找元素
    def find_element_by_text(page,text_str):
        return page.get_by_text(text_str)
    @staticmethod
    #通过location查找元素
    def find_element_by_string(page,string):
        return page.locator(string)
    @staticmethod
    #通过表达式查找元素
    def find_element_by_xpath(page,xpath):
        return page.locator("xpath="+xpath)
    @staticmethod
    #通过id查找元素
    def find_element_by_id(page,id):
        return page.locator("#"+id)
    @staticmethod   
    #通过input/name查找元素
    def find_element_by_input_name(page,name):
        return page.locator("input[name="+name+"]")
    @staticmethod
    #通过type和value查找元素
    def find_element_by_type_value(page,mytype,value):
        return page.locator('input[type="'+mytype+'"][value="'+value+'"]')
    @staticmethod
    #通过name和value查找元素
    def find_element_by_name_value(page,name,value):
        return page.locator('input[name="'+name+'"][value="'+value+'"]')
    @staticmethod
    #通过name查找元素
    def find_element_by_name(page,name):
        return page.locator('input[name="'+name+'"]')
    @staticmethod
    #通过表达式查找元素
    def find_element_by_classname(page,classname):
        return page.locator(".="+classname)
    @staticmethod
    #通过role查找元素
    def find_element_by_role(page,role,value):
        return page.get_by_role(role,name=value)
    @staticmethod
    #通过placeholder查找元素
    def find_element_by_placeholder(page,string):
        return page.get_by_placeholder(string)
    @staticmethod
    #通过文本框值
    def get_text_value(page,mytype):
        return page.input_value('input[type='+mytype+']')
    @staticmethod
    #输入,每次输入都需要清除元素
    def fill(element,str):
        element.fill("")
        element.fill(str)
    @staticmethod
    def save_cookies(page):
        """保存 Cookies 和 Local Storage 到文件"""
        # 1. 保存 Cookies
        cookies = page.context.cookies()
        with open("cookies.pkl", "wb") as f:
            pickle.dump(cookies, f)
        # 2. 保存 Local Storage
        localStorage = page.evaluate("() => JSON.stringify(window.localStorage)")
        with open("localstorage.pkl", "wb") as f:
            pickle.dump(localStorage, f)
    @staticmethod
    def load_cookies(page, url):
        """从文件恢复 Cookies 和 Local Storage"""
        try:
            # 1. 加载 Cookies
            with open("cookies.pkl", "rb") as f:
                cookies = pickle.load(f)
                page.context.add_cookies(cookies)
            # 2. 加载 Local Storage
            with open("localstorage.pkl", "rb") as f:
                localStorageStr = pickle.load(f)
                script = f"""
                    (function(storage) {
  
  {
                        try {
  
  {
                            const entries = JSON.parse(storage);
                            for (const [key, value] of Object.entries(entries)) {
  
  {
                                window.localStorage.setItem(key, value);
                            }}
                        }} catch(e) {
  
  {
                            console.error('LocalStorage 恢复失败:', e);
                        }}
                    }})({localStorageStr});
                """
                page.evaluate(script)
            # 3. 刷新页面使状态生效
            page.goto(url)
            page.reload()
            page.goto("http://127.0.0.1:8000/goods_view/")
        except Exception as e:
            myexception.my_exception(page,f"状态恢复失败: {str(e)}","error_page.png")
    @staticmethod
    def execute_js_script(page,script):
       return page.evaluate(script)

2.1.2 judge类

代码如下​​​​​​​

class judge:
    @staticmethod   
    #判断符合string格式(<td><a href="/update_address/\d/\d/">lable</a></td>)是否存在
    def judge_link_in_td_exists(page,string,lable): 
        # 使用 CSS 选择器查找所有 <td> 下的 <a> 标签
        elements = page.query_selector_all("td a")
        found = False
        for el in elements:
            text = el.text_content().strip()
            href = el.get_attribute("href")            
            if text == lable and re.match(string, href):
                found = True
                break
        return found
    @staticmethod
    
#通过xpath判断元素是否存在
    def judge_by_xpath(page,string):
        element = base.find_element_by_xpath(page,string)
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值