木偶:如何处理多个标签? [英] Puppeteer: How to handle multiple tabs?
问题描述
场景:用于开发人员应用注册的Web表单,包含两部分工作流程.
Scenario: Web form for developer app registration with two part workflow.
第1页:填写开发者应用的详细信息,然后点击按钮以创建应用ID,该ID将在新标签中打开...
Page 1: Fill out developer app details and click on button to create Application ID, which opens, in a new tab...
页面2:应用程序ID"页面.我需要从此页面复制App ID,然后关闭选项卡并返回第1页并填写App ID(从第2页保存),然后提交表单.
Page 2: The App ID page. I need to copy the App ID from this page, then close the tab and go back to Page 1 and fill in the App ID (saved from Page 2), then submit the form.
我了解基本用法-如何打开第1页并单击打开第2页的按钮-但是当在新标签页中打开第2页时如何获得它的手柄?
I understand basic usage - how to open Page 1 and click the button which opens Page 2 - but how do I get a handle on Page 2 when it opens in a new tab?
示例:
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: false, executablePath: '/Applications/Google Chrome.app'});
const page = await browser.newPage();
// go to the new bot registration page
await page.goto('https://register.example.com/new', {waitUntil: 'networkidle'});
// fill in the form info
const form = await page.$('new-app-form');
await page.focus('#input-appName');
await page.type('App name here');
await page.focus('#input-appDescription');
await page.type('short description of app here');
await page.click('.get-appId'); //opens new tab with Page 2
// handle Page 2
// get appID from Page 2
// close Page 2
// go back to Page 1
await page.focus('#input-appId');
await page.type(appIdSavedFromPage2);
// submit the form
await form.evaluate(form => form.submit());
browser.close();
})();
更新2017-10-25
- Browser.pages的工作已已完成和在新标签页创建了#386 和请求:browser.currentPage()或类似的方式来访问第443页.
- The work for Browser.pages has been completed and merged
- Fixes Emit new Page objects when new tabs created #386 and Request: browser.currentPage() or similar way to access Pages #443.
仍在寻找一个很好的用法示例.
Still looking for a good usage example.
推荐答案
这将在最新的alpha分支中为您工作:
This will work for you in the latest alpha branch:
const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page())));
await page.click('my-link');
// handle Page 2: you can access new page DOM through newPage object
const newPage = await newPagePromise;
await newPage.waitForSelector('#appid');
const appidHandle = await page.$('#appid');
const appID = await page.evaluate(element=> element.innerHTML, appidHandle );
newPage.close()
[...]
//back to page 1 interactions
通过将 package.json 依赖项设置为
"dependencies": {
"puppeteer": "git://github.com/GoogleChrome/puppeteer"
},
来源:JoelEinbinder @ https://github.com/GoogleChrome/puppeteer/issues/386#issuecomment-343059315
Source: JoelEinbinder @ https://github.com/GoogleChrome/puppeteer/issues/386#issuecomment-343059315
这篇关于木偶:如何处理多个标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!