playwright-extra用法

1,237 阅读1分钟

简介

playwright包为自动化测试和爬虫提供了便利,node和python都有这个包,做的事情都是一样的,也都是启动浏览器操作DOM,以下只介绍js的代码

# install supported browsers
npx playwright install

启动浏览器

import { chromium } from "playwright-extra";
import stealth from "puppeteer-extra-plugin-stealth";

/**
 * <b color=red>
 * Please don't use proxy server for pages requires login!!!
 * We might leak sensitive data using free proxy server!!!
 * </b>
 *
 * @param profile - browser profile
 * @param useProxyServer - to use proxy server or not
 * @param headless - to display the GUI or not
 */
async function newChromium(profile?: String, useProxyServer: boolean = false, headless?: boolean) {
  const stealthPlugin = stealth();
  chromium.use(stealthPlugin);
  const userDataDir = `data/profiles/chromium-${profile || 'default'}`;
  // const browser = await chromium.launch({headless: headless != null ? headless : true,});
  // const ctx = await browser.newContext();
  // return ctx;
  const launchOptions = {
      headless: true,
      slowMo: 50,
      timeout: 60 * 60 * 1000,
      ignoreHTTPSErrors: true,
      bypassCSP: true,
      // proxy: {
      //   server: 'http://127.0.0.1:8888',
      // },
    }
  // 这里的配置可以调试下
  return chromium.launchPersistentContext(userDataDir, {
    serviceWorkers: 'block',
    ...launchOptions,
    headless: headless != null ? headless : true,
    ...(getProxyServer(useProxyServer)),
  });
}

browserContext = await newChromium(opsAcc.id, false, false);
page = await browserContext.newPage();

模拟点击输入,如登录操作

await page.goto('某个地址', {timeout: 30_000,});

// 如果有账号需要登录
await page.locator('[id="email-phone"]').click();
await page.locator('[id="email-phone"]').fill('填入你的账号');


await page.locator('[id="password-input"]').click();
await page.locator('[id="password-input"]').fill(填入你的密码);
// click点击事件
await page.locator('button[type="submit"]').click();

操作DOM,修改DOM元素,随意举例

await page.evaluateHandle((account) => {
    console.log('account', account)
    const style = `<style type="text/css">
    .aaa {
      background-color: var(--G500,#03AC0E);
      border: none;
      border-radius: 8px;
      color: rgb(255, 255, 255);
      cursor: pointer;
      display: block;
      font-family: inherit;
      font-weight: 700;
      font-size: 1rem;
      height: 40px;
      line-height: 20px;
      outline: none;
      position: relative;
      padding: 0px 16px;
      text-indent: initial;
      transition: background-color 300ms ease 0s;
      width: 100%;
      margin-bottom: 16px;
    }
    </style>`;
    const styleElement: any = document.createElement('div');
    styleElement.innerHTML = style;
    document.getElementsByTagName('head')[0].appendChild(styleElement.firstElementChild);
    const emailPhoneSubmit = document.querySelector('button[type="submit"]');
    emailPhoneSubmit?.removeAttribute('disabled');
    emailPhoneSubmit?.classList.remove('bbb');
    emailPhoneSubmit?.classList.add('aaa');
    const emailPhoneInput = document.getElementById('email-phone');
    emailPhoneInput?.setAttribute('value', account);
    emailPhoneInput?.dispatchEvent(new Event('input'));
}, account)

关闭浏览器

await browserContext.close();