如何登录Puppeteer? [英] How to login in Puppeteer?
问题描述
我是javascript和puppeteer的新手。
我在下面尝试了一个登录代码并失败了。
相比之下,我添加了pages2并成功了。
我该如何解决?
提前致谢。
I'm new to javascript and puppeteer. I tried a login code below and failed. In comparison, I added pages2 and succeeded. How can I solved it? Thanks in advance.
const CREDS = require('./creds');
async function main() {
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setViewport({width: 1200, height: 720})
await page.goto('https://www.daum.net');
await page.waitForNavigation();
await page.type('#id', CREDS.username);
await page.type('#loginPw', CREDS.password);
await page.click('#loginSubmit');
const page2 = await browser.newPage();
await page2.setViewport({width: 1200, height: 720})
await page2.goto('https://google.com');
await page2.type('#lst-ib', 'Headless Chrome');
}
main();
推荐答案
page.waitForNavigation() ;
在点击
或从页面触发的任何导航操作后等待导航。你应该在page.click之后添加waitForNavigation。 / p>
page.waitForNavigation();
waits for navigation after a click
or any navigation action that triggers from the page.you should probably add the waitForNavigation after the page.click.
await Promise.all([
page.click('#loginSubmit'),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
它会等到两个承诺结算。
It will wait until both promises resolves.
所以现在你的初始代码看起来像这样,
So now your initial code would look like this,
const puppeteer = require('puppeteer');
async function main() {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setViewport({width: 1200, height: 720})
await page.goto('https://www.daum.net', { waitUntil: 'networkidle0' }); // wait until page load
await page.type('#id', CREDS.username);
await page.type('#loginPw', CREDS.password);
// click and wait for navigation
await Promise.all([
page.click('#loginSubmit'),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
}
main();
注意:回答一下,我无法测试这个,因为我没有<$ c的登录$ c> daum.net ,我看不到您面临的实际错误。如果您可以尝试上面提供的解决方案并分享结果,那将会更有帮助。
Note: Answer aside, I cannot test this since I don't have a login for daum.net
and I cannot see the actual error you are facing. If you can try the solution provided above, and share the results, it'd be much more helpful.
这篇关于如何登录Puppeteer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!