如何使用JS将Selenium IDE提取的HTML表格快速转换为JSON格式
JS解析HTML表格转JSON实现方案
完全可以通过JavaScript的原生DOM解析能力实现快速转换,性能远高于Selenium逐元素定位提取,适合处理大型表格场景,实现代码如下:
// 你已有的表格HTML字符串变量 var htmlTable = '<table id="customers"> ... </table>' // 创建临时DOM容器解析HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = htmlTable; const table = tempDiv.querySelector('#customers'); const rows = table.querySelectorAll('tr'); // 提取表头作为JSON的键 const headers = Array.from(rows[0].querySelectorAll('th')).map(th => th.textContent.trim()); // 遍历数据行生成JSON数组 const result = []; for (let i = 1; i < rows.length; i++) { const cells = Array.from(rows[i].querySelectorAll('td')).map(td => td.textContent.trim()); const rowObj = {}; headers.forEach((header, index) => { rowObj[header] = cells[index] || ''; }); result.push(rowObj); } // 输出最终JSON,可按需存储 const jsonResult = JSON.stringify(result, null, 2); console.log(jsonResult);
注意事项
- 代码可直接在Selenium IDE的
execute script步骤中运行,直接拿到转换后的JSON结果 - 如果你的表格没有id属性,把
querySelector('#customers')改成querySelector('table')即可匹配页面第一个表格 - 代码默认自动去除了表头和单元格内容前后的多余空格,避免出现示例中
Contact带空格的异常键名 - 万级行的表格转换耗时基本在毫秒级,远快于Selenium逐元素读取的方案
内容的提问来源于stack exchange,提问作者BadRobot
相关产品推荐
相关产品推荐

