javascript - Puppeteer 如何将结果存储在对象变量中?
问题描述
如何将数据存储在对象变量中。我以为我熟悉对象变量,但我猜不是。我正在尝试像这样存储我的数据。
Product:{
Title: Bla Bla Bla
}
Product:{
Title: Ala Ala Ala
}
这是我目前拥有的代码。
const puppeteer = require('puppeteer');
(async () => {
let movieURL = 'https://www.walmart.com/search/?query=&cat_id=91083';
let productName = []
let browser = await puppeteer.launch({ headless: true});
let page = await browser.newPage();
await page.goto(movieURL, {waitUntil: 'networkidle2'});
let data = await page.evaluate(() => {
productName = [...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)
return{
productName
}
})
console.log(data);
await browser.close()
})();
我得到的结果是这样的。
{
productName: [
'SQ Non Chlorinated Brake Parts Cleaner',
'Super Tech DEF Diesel Exhaust Fluid, 2.5 Gallon',
'Mobil 1 Advanced Fuel Economy Full Synthetic Motor O ...\n',
]
}
如果你们中的任何人可以提供帮助,请提前感谢您。:) 这是我已经尝试过的一些事情。
productName += [...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)
productName[data] = {[...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)}
productName = {[...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)}
以上所有这些都会出错并且不起作用。
解决方案
你可以在你map()
做类似的事情:
(a) => ({ Product: { Title: a.innerText } })
const puppeteer = require("puppeteer");
(async () => {
let movieURL = "https://www.walmart.com/search/?query=&cat_id=91083";
let productName = [];
let browser = await puppeteer.launch({ headless: true });
let page = await browser.newPage();
await page.goto(movieURL, { waitUntil: "networkidle2" });
let data = await page.evaluate(() => {
productName = [
...document.querySelectorAll("a.product-title-link"),
].map((a) => ({ Product: { Title: a.innerText } }));
return {
productName,
};
});
console.log(data);
await browser.close();
})();
推荐阅读
- python - 如果给定一个 Python 类,我该如何运行它并查看它的作用?
- php - 如何在 Heroku 上部署静态 Web 应用程序
- reactjs - function_name()() 中的语法
- javascript - 由于某些情况并且未命中 API,如何在 Postman 的预请求脚本中进行测试失败?
- kubernetes - 在 gke 中配置特征门时出错
- javascript - 将基于 javascript 的待办事项列表中的 localStorage 数据推送到 mysql 数据库
- node.js - 在新域上使用 Let's Encrypt with Nginx 和 Node.js 时出现 502 Bad Gateway
- java - Android 资源链接失败(在 Google 上找不到任何专门解决此问题的内容)
- php - PHP curl post/put中的编码
- python - 将多行for循环更改为单行for循环