美文网首页
Puppeteer 自己封装的好用的函数

Puppeteer 自己封装的好用的函数

作者: DjangoUnchained | 来源:发表于2020-09-09 11:51 被阅读0次

会不断更新!!!

依赖

  • puppeteer
  • expect-puppeteer
const expect = require('expect-puppeteer');
const puppeteer = require('puppeteer');

函数

1. 上传文件

filePath:从执行命令行的上下文开始算起

async function uploadfile(page, elementSelector, filePath) {
    const inputUploadHandle = await page.$(elementSelector);
    await inputUploadHandle.uploadFile(filePath);
}
2. 校验元素中包含指定字符
async function assertElementHaveText(page, elementSelector, assertText) {
    await page.waitFor(elementSelector, {visible: true});
    const element = await expect(page).toMatchElement(elementSelector, {timeout: 15000});
    await expect(element).toMatch(assertText);
}
3. 通过字符找到元素并点击

tag: 比如 'a', 'li'

async function clickElementByText(page, tag, text) {
    await page.waitFor(500);
    await expect(page).toMatch(text, {timeout: 5000});
    await expect(page).toClick(tag, {text: text});
    await page.waitFor(500);
}
4. 屏蔽指定的域名list

blockList: ['']

async function blockDomainsList(page, blockList){
    await page.setRequestInterception(true);

    page.on('request', interceptedRequest => {
        if (blockList.includes(new URL(interceptedRequest.url()).host)) {
            interceptedRequest.abort();
        } else {
            interceptedRequest.continue();
        }
    })
}
5. 清除输入框中的内容,并输入

puppeteer中好像没有自带清除的参数

async function clearAndType(page, elementSelector, text) {
    const ainput = await page.$(elementSelector);
    await ainput.click({ clickCount: 3 });
    await ainput.press('Backspace');
    await page.type(elementSelector, text);
}
6. 等待某个url请求返回
await page.waitForResponse(response => {
    // return里书写类似以下语句
    return response.request().url().includes('api/v1/my/url');
});
7. 校验当前页面url是否正确
async function assertCurrentUrl(page, url) {
    const currentUrl = await page.evaluate(() => location.href);
    if (currentUrl.indexOf(url) < 0) {
        throw new Error('url not in current url')
    }
}
8. 允许下载文件
await page._client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        // This path must match the WORKSPACE_DIR in Step 1
        downloadPath: path.join(process.cwd() , 'download')
});
9. 通过Xpath点击元素
async function clickByXpathText(page, tag, text){
    const xpath = `//${tag}[text()='${text}']`;
    await page.waitForXPath(xpath, {visible: true});
    await page.waitForTimeout(500);
    const elements = await page.$x(xpath);
    await elements[0].click();
}
10. 判断元素是否可见
async function elementIsHidden(page, elementSelector) {
    const isHidden = await page.$eval(elementSelector, (elem) => {
        return elem.style.display === 'none'
    });
    return isHidden;
}
11. 依次点击匹配的元素
async function clickEveryone(page, selector='', x_path=''){
    let elHandleArray = '';
    if (selector){
        await page.waitForSelector(selector);
        elHandleArray = await page.$$(selector);
    }
    if (x_path){
        await page.waitForXPath(x_path);
        elHandleArray = await page.$x(x_path);
    }
    if (!elHandleArray){
        throw new Error('没有找到要点击的元素');
    }
    elHandleArray.forEach(async el => {
        await el.click({delay:50}).catch(()=>{
            //console.log('try click every downside confirm')
        })
    });
}
12. 发送请求并获取返回结果
async function getToken(attr){
    return new Promise(resolve => {
        let obj='';
        const data = JSON.stringify({
            username: attr["username"],
            password: attr["password"]
        });
        const options = {
            hostname: attr["base_url"],
            port: 443,
            path: '/pa/api/auth/login',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': data.length
            }
        };
        callback = function(response){
            var str='';
            response.on('data',function(chunk){
                str+=chunk;
            });
            response.on('end',function(){
                obj=JSON.parse(str);
                resolve(obj);
            });
        };

        let request = https.request(options,callback);
        request.write(data);
        request.end();
    });
}
13. 滚动屏幕
    await page.evaluate(_ => {
        window.scrollBy(0, 600);
    });
14. 滚动元素至可见
await page.evaluate((element_selector) => {
    document.querySelector(element_selector).scrollIntoView();
}, element_selector);
15. 控制新页面
    const newPagePromise = new Promise(res =>
        browser.once('targetcreated',
            target => res(target.page())
        )
    );
    // 执行打开新页面操作
    const page2 = await newPagePromise;
    await page2.bringToFront();
16. 获取元素属性值
async function getElementAttribute(page, selector, attribute) {
    return await page.$eval(selector, (el,attribute)=>
        el.getAttribute(attribute), attribute)
}

相关文章

  • Puppeteer 自己封装的好用的函数

    会不断更新!!! 依赖 puppeteer expect-puppeteer 函数 1. 上传文件 filePat...

  • Puppeteer相关介绍

    最近在使用lighthouse和puppeteer进行一些性能测试相关的工作,感觉puppeteer还是很好用的,...

  • class: Puppeteer

    类Puppeteer是所有例子的开始。 1:puppeteer.connect(options) 该函数用于连接一...

  • 34

    完成了30多个流程还差10左右,越发觉得函数封装的重要性,以及低耦合,高内聚的重要性了,前期封装的函数感觉挺好用,...

  • JRDB:iOS对FMDB的超好用封装

    JRDB:iOS对FMDB的超好用封装 JRDB:iOS对FMDB的超好用封装

  • 封装自己的Ajax函数

    1. 要实现的效果 2. 定义options参数选项 myAjax() 函数是我们自定义的 Ajax 函数,它接收...

  • 封装自己的Jsonp函数

    1. jsonp的实现原理: 2. 将对象转换成查询字符串 3. 定义 myJsonp 函数 4. 给src属性设置值

  • 总结简化版jQuery

    自己封装两个函数 封装函数的方法。这两个函数分别为: getSiblings 函数的功能为获取传入节点的所有"兄弟...

  • js面向对象:封装

    封装 1.不合理:构造函数模式的问题 构造函数方法很好用,但是存在一个浪费内存的问题。请看,我们现在为Cat对象添...

  • JavaScript基础—函数

    函数基础 函数声明: 如果函数不调用,自己是不会执行的: 函数的封装:是把一个或多个功能通过函数的方式封装起来并对...

网友评论

      本文标题:Puppeteer 自己封装的好用的函数

      本文链接:https://www.haomeiwen.com/subject/xnleektx.html