Blue
Blue

Reputation: 251

Using Puppeteer to type in inputs

So I've been trying to work with puppeteer, and honestly it has been hassle but I am determined to get a better understanding of it.

So I am trying to use the Page.Type() function, and I am having trouble with it either finding the inputs or... what I think might be causing the issue is that my internet is too slow and it's not able to find the selectors...

But I had thought that the

await instagram.page.waitForNavigation({ waitUntil: 'networkidle2' });

Would've solved the issue, maybe I am doing something else wrong I am not sure.

Here are the files :

main.js -

 const insta = require('./instagram');

(async () => {

    await insta.initialize();

    await insta.login('user', 'password');

    debugger;
})()

instagram.js -

    const puppeteer = require('puppeteer');

const BASE_URL = 'https://instagram.com/';

const instagram = {
    browser: null,
    page: null,

    initialize: async () => {

        instagram.browser = await puppeteer.launch({
            headless: false
        });

        instagram.page = await instagram.browser.newPage();

    },

    login: async (username, password) => {

        await instagram.page.goto(BASE_URL, { waitUntil: 'networkidle2' });

        let loginButton = await instagram.page.$x('//*[@id="loginForm"]/div/div[3]/button')

        await loginButton[0].click();

        await instagram.page.waitForNavigation({ waitUntil: 'networkidle2' });

        await instagram.page.waitFor(1000);

        await instagram.page.type('input[name="username"]', username, { delay: 500 });
        await instagram.page.type('input[name="password"]', password, { delay: 500 });

        debugger;
    }

}

module.exports = instagram;

Upvotes: 0

Views: 256

Answers (1)

Todd Price
Todd Price

Reputation: 2760

Your login: function should look like this:

    login: async (username, password) => {
        await instagram.page.goto(BASE_URL, { waitUntil: 'networkidle2' });
        await instagram.page.waitForNavigation({ waitUntil: 'networkidle2' });
        await instagram.page.waitFor(1000);
        await instagram.page.type('input[name="username"]', username, { delay: 500 });
        await instagram.page.type('input[name="password"]', password, { delay: 500 });

        const loginButton = await instagram.page.$x('//*[@id="loginForm"]/div/div[3]/button');

        await Promise.all([
          this.page.waitForNavigation(),
          loginButton[0].click();
        ]);

        debugger;
    }

You were clicking the login button before you filled in the inputs. Also, the Promise.all block as I've shown is the recommended way to click a button that navigates to a new URL.

Upvotes: 1

Related Questions