我正在尝试登录Moz在https://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/