How can I pause and wait for user input with Puppeteer?

人盡茶涼 提交于 2019-12-12 18:31:07

问题


I need to make Puppeteer pause and wait for user input of username and password before continuing. It is a nodejs 8.12.0 app.

(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();   
    await page.goto('https://www.myweb.com/login/');

    //code to wait for user to enter username and password, and click `login`

    const first_page = await page.content();

   //do something 

    await browser.close();
)}();

Basically the program is halted and waits until the user clicks the login button. Is it possible to do this in Puppeteer? Or what else can I do?


回答1:


You can use page.waitForFunction() to wait for a function to return a truthy value before continuing.

The following function will wait until the #username and #password fields contain a value before continuing:

await page.waitForFunction(() => {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  return username.length !== 0 && password.length !== 0;
});

But since you are entering the #username and #password yourself, you can simply use:

await page.type('#username', 'username');
await page.type('#password', 'password');
await page.click('#login');
await page.waitForNavigation();


来源:https://stackoverflow.com/questions/52998673/how-can-i-pause-and-wait-for-user-input-with-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!