javascript - Pass variable into page.evaluate
问题描述
I have searched for passing variables, but I'm not successful. It returns the 'data' as undefined. Please help me to fix this!
const details = (
await Promise.allSettled(
datas
.map(async (data) => {
const page = await browser.newPage();
await page.goto(data.link, {
waitUntil: "networkidle2",
});
return await page.evaluate((data) => {
return {
regular_price: document.querySelector(data.regular_price_class)
? document.querySelector(data.regular_price_class).innerText.replace(/[\$,\D]/g, "")
: "",
sale_price: document.querySelector(data.sale_price_class)
? document.querySelector(data.sale_price_class).innerText.replace(/[\$,\D]/g, "")
: "",
online_sale_price: document.querySelector(data.online_sale_price_class)
? document.querySelector(data.online_sale_price_class).innerText.replace(/[\$,\D]/g, "")
: "",
promotion: document.querySelector(data.promotion_class)
? document.querySelector(data.promotion_class).innerText.replace(/[\$,\D]/g, "")
: "",
};
});
}, data)
)
)
解决方案
现在,您将data
作为第二个参数传递给.map
,这没有意义:
const details = (
await Promise.allSettled(
datas
.map(async (data) => {
// ...
}, data)
)
)
相反,您需要将其传递给page.evaluate
:
const details = (
await Promise.allSettled(
datas
.map(async (data) => {
const page = await browser.newPage();
await page.goto(data.link, {
waitUntil: "networkidle2",
});
return await page.evaluate((data) => {
return {
// ...
};
}, data);
})
)
)
我还推荐一个提取价格的函数,让事情变得更加干燥:
return page.evaluate((data) => {
const getPrice = selector => (document.querySelector(selector)?.innerText || '').replace(/[\$,\D]/g, "");
return {
regular_price: getPrice(data.regular_price_class),
sale_price: getPrice(data.sale_price_class),
online_sale_price: getPrice(data.online_sale_price_class),
promotion: getPrice(data.promotion_class),
};
}, data);
推荐阅读
- java - JPA:将记录批量插入元素集合
- c - 如何在 Linux 的 system() 中接受多个参数
- mysql - SQL 为变量赋值,但从另一行获取该值
- c - 尝试打印具有特定数字长度的数组元素,但 main() 似乎没有执行
- anylogic - 如何使用 anylogic 中的状态图控制单个行人类型代理的行为?
- c++ - 如何从 cmake 子项目中删除或覆盖编译标志
- powershell - 如何使用 powershell 更新 xml 属性值
- python - pandas groupby 根据唯一值扩展 df
- java - 导入 sun.security.ec 无法解决
- android-studio - 如何在单行注释后阻止 Android Studio 缩进下一行