如何通过类名获取元素data-id值并存入数组?Playwright问题解决
Solution to Extract
data-id Values into Array Issues with the Original Code
page.$$evalpasses an array of matched elements to the callback function, not a single element. Your code tried to destructuredata-iddirectly from this array, which is invalid.- Hyphenated attributes like
data-idcan’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-1q11k9ais more robust thandiv[class='tr svelte-1q11k9a']because it doesn’t depend on the order of classes in the HTML. $$evalexecutes the callback in the browser’s context, so all element operations must be valid in the browser environment.
内容的提问来源于stack exchange,提问作者James Andrews
相关产品推荐
相关产品推荐

