无星的自动化之旅(三)——PlayWright配置项和常见功能业务

814 阅读2分钟

这次我们来聊一聊playwright的一些配置项

一、登录保存数据

网站每次都要登录,很烦,没必要

所以我们登录之后,可以把cookie或者session什么的保存起来

下次登录再把数据注入

这样就不用再登录了

1.先正常登录

就写代码登录

2.保存数据

通过context.storageState保存数据到本地文件 例如:

   // 保存登录状态
    await context.storageState({
        path: dirPath + '/auth/auth.json',
    })

3.回到初始化,生成brower时,通过文件注入

const authState = require('../auth/auth.json')
const browser = await chromium.launch({
        headless: false,
        // 使用edge浏览器
        channel: 'msedge',
    });
    const context = await browser.newContext({
        storageState: authState ?? {},
    });
    const page = await context.newPage({
    });

二、忽略不安全的https

自签名证书,这个很常见。

很多情况下,使用自签名证书做测试环境或者内网环境的https,是一种非常常见且低成本的https方式。

但是自签名证书因为没有CA认证,浏览器会报非专用链接提示

playwright在访问此类地址时,也会有相同的提示,导致无法进行正常的自动化工作。

我们可以通过配置playwright的设置项,让浏览器默认忽略此类问题。

    const browser = await chromium.launch({
        headless: false,
        // 使用edge浏览器
        channel: 'msedge',
    });
    const context = await browser.newContext({
        storageState: authState ?? {},
        // 忽略https的问题
        ignoreHTTPSErrors: true
    });
    const page = await context.newPage({
    });

三、上传文件

有些网页流程中,需要上传文件。

例如发邮件时需要上传附件

这时候就有点犯难,因为上传文件的框,它不是网页,它是Windows程序

其实playwright对此已有处理,使用fileChooser即可

        // 文件路径,绝对路径!
        const filePath = 'xxxx'
        const fileChooserPromise = page.waitForEvent('filechooser');
        await page.click('text=添加附件');
        const fileChooser = await fileChooserPromise;
        await fileChooser.setFiles(filePath);

四、下载文件

比如把文件下载在当前项目路径下等

    const [download] = await Promise.all([
        // 指定等待下载事件
        page.waitForEvent('download'),
        // 点击下载元素
        mainFrame.locator('xpath=xxx').click(),
    ]);
    // 获取文件下载路径
    // const path = await download.path();
    // 获取文件全称,含后缀
    // const fileName = download.suggestedFilename();
    // 自己设置文件名称
    const fileName = 'xxxx'
    // 保存文件,参数为文件路径
    await download.saveAs('filepath');