【发布时间】:2020-12-28 05:04:23
【问题描述】:
我正在尝试使用 Puppeteer 提取此页面的标题:https://www.nordstrom.com/s/zella-high-waist-studio-pocket-7-8-leggings/5460106
我有以下代码,
(async () => {
const browser = await puppet.launch({ headless: true });
const page = await browser.newPage();
await page.goto(req.params[0]); //this is the url
title = await page.evaluate(() => {
Array.from(document.querySelectorAll("meta")).filter(function (
el
) {
return (
(el.attributes.name !== null &&
el.attributes.name !== undefined &&
el.attributes.name.value.endsWith("title")) ||
(el.attributes.property !== null &&
el.attributes.property !== undefined &&
el.attributes.property.value.endsWith("title"))
);
})[0].attributes.content.value ||
document.querySelector("title").innerText;
});
我已经使用浏览器控制台进行了测试,甚至使用了 Puppeteer 的 { headless: false } 选项。它在浏览器中按预期工作,但是当我实际使用节点运行它时,它给了我以下错误。
10:54:21 AM web.1 | (node:10288) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'attributes' of undefined
10:54:21 AM web.1 | at __puppeteer_evaluation_script__:14:20
所以,当我在浏览器中运行相同的 Array.from ...querySelectorAll("meta")... 查询时,我得到了预期的字符串:
"Zella High Waist Studio Pocket 7/8 Leggings | Nordstrom"
我开始认为我对异步承诺做错了,因为那是不同的部分。谁能指出我正确的方向?
编辑:按照建议,我使用 document.title 进行了测试,它应该在那里,但它也返回 null。请参阅下面的代码和日志:
console.log(
"testing the return",
(async () => {
const browser = await puppet.launch({ headless: true });
const page = await browser.newPage();
await page.goto(req.params[0]); //this is the url
try {
title = await page.evaluate(() => {
const title = document.title;
const isTitleThere = title == null ? false : true;
//recently read that this checks for undefined as well as null but not an
//undeclared var
return {
title: title,
titleTitle: title.title,
isTitleThere: isTitleThere,
};
});
} catch (error) {
console.log(error, "There was an error");
}
11:54:11 AM web.1 | testing the return Promise { <pending> }
11:54:13 AM web.1 | { title: '', isTitleThere: true }
这与单页应用程序bs有关吗?我认为 puppeteer 处理了这个问题,因为它首先加载所有内容。
编辑:按照建议,我添加了 networkidle 行并等待 8000 毫秒。标题仍然是空的。下面的代码和日志:
await page.goto(req.params[0], { waitUntil: "networkidle2" });
await page.waitFor(8000);
console.log("done waiting");
title = await page.$eval("title", (el) => el.innerText);
console.log("title: ", title);
console.log("done retrieving");
12:36:39 PM web.1 | done waiting
12:36:39 PM web.1 | title:
12:36:39 PM web.1 | done retreiving
编辑:进展!! 感谢大卫巴顿。似乎无头必须是假的才能起作用?有谁知道为什么?
【问题讨论】:
标签: javascript node.js web-scraping puppeteer