Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - How to login in Puppeteer?

I'm new to JavaScript and Puppeteer. I tried the login code below, but it failed. In comparison, I added page2 and succeeded. How can I solve it?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...