利用puppeteer 公众号自动导入回复信息

准备工作

首先得申请一个微信公众号,然后用浏览器登录之后,来到关键词回复页面。利用cookie获取工具导出当前的cookie。

点击导出当前domain的所有cookie

导出来的cookie是一个数组,直接复制到一个地方备用即可

环境构建

使用全局代理,利用npm下载puppeteer

npm i [email protected]

由于下载puppeteer的时候会下载chromium,所以需要全局代理,不下载chromium也可以直接下载puppeteer-core

npm i puppeteer-core

整活

打开页面
let browser = await puppeteer.launch(launchOptions);
let page = await browser.newPage();
for (let i = 0; i < cookies.length; i++) {
    await page.setCookie(cookies[i]);
}
await page.goto(url);
await page.waitForSelector('html');
await page.content();
let title = await page.title();
点击添加回复
await page.$$eval('.weui-desktop-layout__extra', clickAddButton);
async function clickAddButton(nodes) {
    let cnt = 0;
    for (let node of nodes) {
        cnt++;
        if (cnt === 1) continue;
        let treeWalker = document.createTreeWalker(
            node,
            NodeFilter.SHOW_ELEMENT,
            {
                acceptNode: function (node2) {
                    return NodeFilter.FILTER_ACCEPT;
                }
            },
            false
        );
        while (treeWalker.nextNode()) {
            let current = treeWalker.currentNode;
            if (current.tagName.toLowerCase() === 'button' && current.innerHTML === '添加回复') {
                await current.click();
                return true;
            }
        }
    }
    return false;
}
填写规则和匹配
await page.type('.weui-desktop-form__input', val.group + '', {delay: 100});
await page.waitFor(1000);
await page.type('[placeholder=输入关键词]', val.title.split('-')[0] + '', {delay: 100});
await page.waitFor(1000);

点击添加文本回复信息的按钮

await page.$$eval('.weui-desktop-msg-sender__tab_text', addTxt);
async function addTxt(nodes) {
    for (let node of nodes) {
        await node.click();
        return true;
    }
    return false;
}
在内容区键入回复内容
await page.focus('.edit_area');
await page.keyboard.type('aaa:' + val.title.split('-')[0].trim(), {delay: 100});
await page.keyboard.press('Enter');
await page.keyboard.type('bbb:' + val.title.split('-')[1].trim(), {delay: 100});
await page.keyboard.press('Enter');
await page.keyboard.type('ccc:' + val.url, {delay: 100});
await page.keyboard.press('Enter');
await page.keyboard.type('ddd:' + val.code, {delay: 100});
await page.keyboard.press('Enter');
await page.keyboard.type('eee:' + val.id, {delay: 100});
利用xpath点击按钮
await page.waitForXPath('//*[@id="app"]/div[3]/div[2]/div[2]/form/div[3]/div/div/div[3]/div[1]/div/div[3]/button[1]');
let elHandles = await page.$x('//*[@id="app"]/div[3]/div[2]/div[2]/form/div[3]/div/div/div[3]/div[1]/div/div[3]/button[1]');
for (let handle of elHandles) {
    handle.click({delay: 100});
}
利用xpath 点击保存按钮
await page.waitForXPath('//*[@id="app"]/div[3]/div[2]/div[2]/div/button[1]');
let elHandle1s = await page.$x('//*[@id="app"]/div[3]/div[2]/div[2]/div/button[1]');
for (let handle of elHandle1s) {
    handle.click({delay: 100});
}

就搞定了

炒鸡辣鸡原创文章,转载请注明来源

你可能感兴趣的:(利用puppeteer 公众号自动导入回复信息)