How to login in Puppeteer?

后端 未结 2 1133
陌清茗
陌清茗 2020-12-13 19:43

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?



        
相关标签:
2条回答
  • 2020-12-13 20:12

    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.

    0 讨论(0)
  • 2020-12-13 20:12

    page.waitForNavigation()

    Logging in to a website using Puppeteer is generally as simple as using the following code:

    await page.goto('https://www.example.com/login');
    
    await page.type('#username', 'username');
    await page.type('#password', 'password');
    
    await page.click('#submit');
    
    await page.waitForNavigation(); // <------------------------- Wait for Navigation
    
    console.log('New Page URL:', page.url());
    

    Note: Remember to use page.waitForNavigation() after clicking the submit button to wait for the home page to display before moving forward.

    0 讨论(0)
提交回复
热议问题