我需要一个例子,如何用puppeteer切换标签
这是我现在所拥有的:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false, // launch headful mode
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('https://URL1.com');
const pagee = await browser.newPage();
await pagee.setViewport({ width: 1920, height: 1080 });
await pagee.goto('https://URL2.com');
})();
因此它首先打开2个标签:Url1,第二个:Url2
我需要什么:
第一个Tab做一些动作...... 转到第二个Tab做一些动作...... 回到第一个Tab做一些动作......
你能告诉我一个例子吗?谢谢
答案 0 :(得分:0)
您需要的代码是page.bringToFront
See here
下面的工作脚本。请注意我在选项卡切换之间添加了wait
,否则脚本会快速运行:)
const puppeteer = require('puppeteer');
async function run() {
const browser = await puppeteer.launch( {
headless: false
});
const page1 = await browser.newPage();
await page1.goto('https://www.google.com');
const page2 = await browser.newPage();
await page2.goto('https://www.bing.com');
const pageList = await browser.pages();
console.log("NUMBER TABS:", pageList.length);
//switch tabs here
await page1.bringToFront();
blockingWait(1);
await page2.bringToFront();
blockingWait(1);
await page1.bringToFront();
blockingWait(4);
await browser.close();
};
function blockingWait(seconds) {
//simple blocking technique (wait...)
var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}
}
run();