如何使用 Puppeteer 的 evaluate 或 eval 方法创建一个对象或关联数组?

huangapple go评论61阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2023年3月4日 06:53:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定