随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(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
}
}