node.js - 无法使用 Puppeteer 登录

标签 node.js web-scraping puppeteer

我正在尝试登录Mozhttps://moz.com/login使用 Puppeteer 使用以下代码:

const puppeteer = require('puppeteer');

const creds = {
    email: "myemail",
    password: "mypassword"
};

(async () => {
  const browser = await puppeteer.launch({
    args: [
        '--disable-web-security',
      ],
      headless: false
    });
  const page = await browser.newPage();

    await page.goto("https://moz.com/login");
    await page.$eval("input[name=email]", (el, value) => el.value = value, creds.email);
    await page.$eval("input[name=password]", (el, value) => el.value = value, creds.password);
    await Promise.all([
        page.$eval("input[type=submit]", elem => elem.click()),
        page.waitForNavigation({ waitUntil: 'networkidle0' }),
    ]);

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

我知道我传递的电子邮件和密码是正确的,因为我可以使用它们手动登录,但是当我运行上面的脚本时,我在表单上方收到“无效的电子邮件或密码”错误。

Chrome 中的 JS 控制台记录了两个错误:

Failed to load resource: the server Failed to load resource: the server responded with a status of 404 () cs.moz.com/id?d_visid_ver=1.10.0&d_fieldgroup=A&mcorgid=2C702C1653CF9B460A490D4B%40AdobeOrg&mid=86471825972219878023490878783607186756&ts=1564059866100:1

Failed to load resource: the server responded with a status of 400 () svc/forge/forms/login:1

对于问题可能是什么有什么想法吗?

最佳答案

发生此错误的原因是您通过执行 javascript 函数 $eval 而不是 type 函数来设置电子邮件和密码。

此外,我建议使用 click 函数而不是 $eval 函数。了解更多关于 the difference between a "trusted" and "untrusted" input event

只需替换这些行:

await page.$eval("input[name=email]", (el, value) => el.value = value, creds.email);
await page.$eval("input[name=password]", (el, value) => el.value = value, creds.password);

有这些:

await page.type('input[name=email]', creds.email);
await page.type('input[name=password]', creds.password)

所以你的最终脚本应该是:

const puppeteer = require('puppeteer');

const creds = {
    email: "myemail",
    password: "mypassword"
};

(async () => {
  const browser = await puppeteer.launch({
    args: [
        '--disable-web-security',
    ],
    headless: false
  });

  const page = await browser.newPage();

  await page.goto("https://moz.com/login");
  await page.type('input[name=email]', creds.email);
  await page.type('input[name=password]', creds.password)
  await Promise.all([
    page.click('input[type=submit]'),
    page.waitForNavigation({ waitUntil: 'networkidle0' }),
  ]);

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

关于node.js - 无法使用 Puppeteer 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202761/

相关文章:

Python Selenium 从 url 中抓取丢失的图像

python - 我正在尝试使用 Xpath 从电视节目中检索脚本,但它返回的是一个空列表

javascript - 通过其子项获取项目 ID (vanilla JS)

puppeteer - 如何根据 `innerText` 获取 ElementHandle ?

node.js - 运行任务时 Gulp 错误 : ENOENT, lstat

node.js - Express 和 Cradle 出现奇怪错误

javascript - node-fetch 不适用于 AWS lambda 函数 ("cannot find node-fetch")

php - 简单的 HTML DOM 解析器和 Web 浏览器返回不同的 HTML

javascript - 如何使用 Puppeteer 选择具有同一类的所有子 div?

node.js - 类型错误 : Cannot read property 'user' of undefined