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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:39:05