puppeteer Switching to New Tab?

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

from:https://github.com/GoogleChrome/puppeteer/issues/978链接里面的

 https://github.com/GoogleChrome/puppeteer/pull/554

原文提供了多种思路去解决puppeteer多个页面切换问题,我采用的是duckywang1的思路:

 

Apologies. I have no experience of unit test.
Yesterday I didn't try this feature seriously. Today I write an example of my business logic with browser.pages(); and headless browser. It worked!
I can interact with page created from a[target="_blank"]. @twalpole

Now I hope this great feature would be merged, althought it only take effect in headless browser temporarily.

Here is my example:
I got two pages.

detail page.
This page provide an HTMLElememt a[target="_blank"] and link to download page
download page.
This page will provide a resource URL and download it in 2-10 second automatically.
Here is my example code(fake code, but it did work):

const browser = initHeadlessBrowser(); // create a Headless browser
const detailPage = browser.newPage();
detailPage.goto(url, '{ waitUntil: 'networkidle' }');
const btn = page.$('.download');
btn.click({ delay: 100 }); // create a download page but we can fetch them with browser.pages();

const allPages = browser.pages();
for (let i = 1; i < allPages.length; i += 1) {
  // allPages[0] is a blank page. We can't get any valid info. If interested, you can open a headless: false browser and see the GUI of Chrominum.
  // compare something with your download page
  // here I confirm it with page.url();
  if (condition) {
    const downloadPage = allPages[i];
    await downloadPage.setRequestInterceptionEnabled(true);
    downloadPage.on('request', request => {
      if (request.url.indexOf('.png') >= 0) {
        // here i use node_modules`download`
        download(request.url).then(streamData => {
          // get streamData and do something fun
        });
      } else {
        request.continue();
      }
    });
    await downloadPage.waitFor(30000); // waiting for loading views
    await downloadPage.close(); // close download page
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值