我在一个项目中使用puppeteer来测试网页,在该页面中,我有几个按钮可以在浏览器中打开一个新标签,我该如何使用puppeteer来处理呢?
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({ defaultViewport: null });
const page = await browser.newPage();
// go to the URL
await page.goto('https://example.com/', {waitUntil: 'networkidle'});
await page.click('.btnId'); //opens new tab with Page 2
// handle Page 2
// process Page 2
// close Page 2
// go back to Page 1
browser.close();
})();
我如何处理第2页?
答案 0 :(得分:2)
希望这有助于解决问题。
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({ defaultViewport: null });
const page = await browser.newPage();
// go to the URL
await page.goto('https://example.com/', {waitUntil: 'networkidle'});
await page.click('.btnId'); //opens new tab with Page 2
// you can make this as dynamic as well depends on the website and use case.
const [tabOne, tabTwo] = (await browser.pages());
// use the tabs Page objects properly
console.log("Tab One Title ",await tabOne.title());
// use the tabs Page objects properly
console.log("Tab Two Title ",await tabTwo.title());
// you can use close property for tab when it's done.
browser.close();
})();
答案 1 :(得分:1)
await page.waitFor(3 * 1000) // wait for new page to open
const pages = await browser.pages() // get all pages
const page2 = pages[pages.length - 1] // get the new page
// process the new page
await page2.close()