Playwright evaluate方法返回Node引用而非预期JSON数组问题求助
问题原因
你直接返回document.querySelectorAll的结果会得到DOM元素引用,Playwright无法直接序列化DOM对象,所以会返回ref:标识的引用数据,而不是你需要的文本内容。
解决方案
在浏览器上下文(evaluate的回调函数里)把DOM元素集合转换成包含文本内容的数组,再返回。具体步骤:
- 用
Array.from()把querySelectorAll返回的NodeList转换成普通数组 - 遍历数组,提取每个按钮的文本内容并去除多余空格
修改后的完整代码:
async evaluateTest(): Promise<any> { const result = await this.page?.evaluate(() => { const buttons = document.querySelectorAll('.menu-visible-columns .btn-xs'); return Array.from(buttons).map(btn => btn.textContent?.trim() || ''); }); this.debugLog(String(result)); const res2 = JSON.stringify(result); return res2; }
说明
这段代码会返回长度为6的数组,第一个元素是"Icon",其余为空字符串(对应无文本的按钮),完全匹配你预期的格式。用textContent?.trim() || ''是为了避免按钮无文本时返回undefined,保证数组元素都是字符串类型。
内容的提问来源于stack exchange,提问作者agnxt
相关产品推荐
相关产品推荐

