You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过类名获取元素data-id值并存入数组?Playwright问题解决

Solution to Extract data-id Values into Array

Issues with the Original Code

  • page.$$eval passes an array of matched elements to the callback function, not a single element. Your code tried to destructure data-id directly from this array, which is invalid.
  • Hyphenated attributes like data-id can’t be accessed via dot notation in object destructuring without proper quoting, but this is irrelevant here since we’re dealing with an array of elements.

Corrected Code

Use map() to iterate over the element array and extract the data-id value using either dataset.id (preferred for data attributes) or getAttribute('data-id'):

// Using dataset property (cleaner for data attributes)
const ex = await page.$$eval("div.tr.svelte-1q11k9a", elements => 
  elements.map(element => element.dataset.id)
);

// Alternative: Using getAttribute
// const ex = await page.$$eval("div.tr.svelte-1q11k9a", elements => 
//   elements.map(element => element.getAttribute('data-id'))
// );

console.log(ex); // Output: ['111', '222', '333']

Key Notes

  • The selector div.tr.svelte-1q11k9a is more robust than div[class='tr svelte-1q11k9a'] because it doesn’t depend on the order of classes in the HTML.
  • $$eval executes the callback in the browser’s context, so all element operations must be valid in the browser environment.

内容的提问来源于stack exchange,提问作者James Andrews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 22:02:08