puppeteer chrome/chrome canary 登录浏览器

如果你的自动化测试场景有需要登录Chrome去authorize的话,肯定会用到这些步骤的
之前用selenium也实验过用本地的profile去模拟已经登录的场景,但是当点击去登录时,页面一直转转转,一片空白,一片空白,空白

转战puppeteer之后,可以正常打开authorization页面耶,这是成功的表现
亲儿子鸭

官方资料显示,在使用puppeteer去操作authorize的时候,不能使用chromium(我本地使用chromium去登录时就没登录上去过),so 需要在launch browser时必须指定要运行的browser(默认是使用chromium),请使用executablePath,Chrome和 Chrome canary都可以支持

executablePath:'/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary',

executablePath:'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',

and then,也需要指定你本地已经登录到浏览器的profile

userDataDir:'~/Documents/Google/Chrome',

本地的profile最好是拷贝到一个路径下,每次要测试authorize的时候,都需要操作一步拷贝的动作,因为每次运行完之后profile都会被新的操作覆盖,不是“干净”的了
摘自官方的代码puppeteer user-data-dir

const puppeteer = require('puppeteer');

(async () => {
  const datadir = '/tmp/profile/';
  const browser = await puppeteer.launch({
      // Ask puppeteer to run Chrome Canary
      executablePath: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary',
      headless: false,
      userDataDir: datadir,
  });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png', fullPage: true });
  await browser.close();

})();

如果launch browser以后,有new一个新的page,新page的登录状态没有带过去,要在自启动的browser上new tab即可

猜你喜欢

转载自blog.csdn.net/weixin_34320159/article/details/87410112