英文:
How to create an object or associative array with puppeteer evaluate or eval methods?
问题
I can easily get some single attribute from set of selectors, but cannot create some sort of object or associative array with some "key" and "value".
This works with 2 attributes
const kefs = await page.$$eval("div[data-event-treeid]", msgs =>
msgs.map(msg => {
return {
name: msg.getAttribute("data-event-treeid"),
textMessage: msg.innerText,
};
})
);
console.log("kefs", kefs);
but I cannot get something like kefs['data-event-treeid']=innerText
const kefs = await page.$$eval('div[data-event-treeid]', (msgs) =>
msgs.map(msg[msgs.getAttribute('data-event-treeid')]) => {
return {
textMessage: msg.innerText
}
})
);
console.log('kefs', kefs);
So I want to get:
kefs = {"111": "Sometext", "222": "SomeOtherText"}
Where keys 111 and 222 are values of 'data-event-treeid' attributes
英文:
I can easily get some single attribute from set of selectors, but cannot create some sort of object or associative array with some "key" and "value".
This works with 2 attributes
const kefs = await page.$$eval("div[data-event-treeid]", msgs =>
msgs.map(msg => {
return {
name: msg.getAttribute("data-event-treeid"),
textMessage: msg.innerText,
};
})
);
console.log("kefs", kefs);
but I cannot get something like kefs['data-event-treeid']=innerText
const kefs = await page.$$eval('div[data-event-treeid]', (msgs) =>
msgs.map((msg[msgs.getAttribute('data-event-treeid')]) => {
return {
textMessage: msg.innerText
}
})
);
console.log('kefs', kefs);
So I want to get:
kefs = {"111": "Sometext", "222": "SomeOtherText"}
Where keys 111 and 222 are values of 'data-event-treeid' attributes
答案1
得分: 1
谢谢 @ggorlen
以下是我可用的代码:
const kefs = Object.fromEntries(
await page.$$eval("div[data-event-treeid]", msgs =>
msgs.map(msg => [
msg.getAttribute("data-event-treeid"),
msg.innerText,
])
)
);
console.log("kefs", kefs);
希望对你有所帮助。
英文:
Thank you @ggorlen
It works for me with
const kefs = Object.fromEntries(
await page.$$eval("div[data-event-treeid]", msgs =>
msgs.map(msg => [
msg.getAttribute("data-event-treeid"),
msg.innerText,
])
)
);
console.log("kefs", kefs);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论