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

如何提取HTML中id为formTbl的表格数据生成JSON或写入数据库

需求说明
  • 读取本地HTML文件,筛选id为formTbl的目标表格
  • 可选需求1:生成键值对格式的JSON,键为每一行第一个td的文本,值为同一行第二个td的文本,空值统一填Blank
  • 可选需求2:将每一行第一个td内容存入数据库表A,第二个td内容存入数据库表B
可行实现方案

Python实现(基于BeautifulSoup)

依赖安装

pip install beautifulsoup4 lxml

1. 生成目标格式JSON

from bs4 import BeautifulSoup
import json

# 替换为你的本地HTML文件路径
with open("test.html", "r", encoding="utf-8") as f:
    html_content = f.read()

soup = BeautifulSoup(html_content, "lxml")
# 定位目标表格
target_table = soup.find("table", id="formTbl")
result_dict = {}

# 遍历表格所有行
for tr in target_table.find("tbody").find_all("tr"):
    tds = tr.find_all("td")
    if len(tds) < 2:
        continue
    # 提取第一个td的字段名,取h3标签的纯文本,去除多余空白
    field_name = tds[0].find("h3", class_="ms-standardheader").get_text(strip=True)
    # 提取第二个td的字段值,空值替换为Blank
    field_value = tds[1].get_text(strip=True) or "Blank"
    result_dict[field_name] = field_value

# 输出符合要求的JSON
json_result = json.dumps(result_dict, ensure_ascii=False, indent=2)
print(json_result)

运行后输出格式示例:

{
  "Name": "X",
  "Name@": "Z",
  "Age": "52",
  "number": "1",
  "Name of File": "Funny Names",
  "date": "1.1.2022"
}

2. 数据插入数据库(以SQLite为例)

在上述代码基础上增加数据库操作逻辑即可:

import sqlite3

# 替换为你的数据库路径
conn = sqlite3.connect("test.db")
cursor = conn.cursor()

# 此处表结构仅为示例,请根据实际业务调整
# 表A结构示例:id INTEGER PRIMARY KEY AUTOINCREMENT, field_name TEXT
# 表B结构示例:id INTEGER PRIMARY KEY AUTOINCREMENT, field_value TEXT, a_id INTEGER
for field_name, field_value in result_dict.items():
    # 插入表A,获取生成的主键ID
    cursor.execute("INSERT INTO 表A (field_name) VALUES (?)", (field_name,))
    a_id = cursor.lastrowid
    # 关联表A主键插入表B
    cursor.execute("INSERT INTO 表B (field_value, a_id) VALUES (?, ?)", (field_value, a_id))

conn.commit()
conn.close()

C#实现(基于HtmlAgilityPack)

依赖安装

通过NuGet包管理器安装HtmlAgilityPack,需要生成JSON则额外安装Newtonsoft.Json。

代码示例

using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // 替换为你的本地HTML文件路径
        string htmlPath = @"C:\test.html";
        string htmlContent = File.ReadAllText(htmlPath);
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(htmlContent);
        
        // 定位目标表格
        HtmlNode tableNode = doc.DocumentNode.SelectSingleNode("//table[@id='formTbl']");
        Dictionary<string, string> resultDict = new Dictionary<string, string>();

        // 遍历所有行
        foreach (HtmlNode trNode in tableNode.SelectNodes(".//tbody/tr"))
        {
            HtmlNodeCollection tds = trNode.SelectNodes("./td");
            if (tds.Count < 2) continue;
            // 提取字段名
            string fieldName = tds[0].SelectSingleNode(".//h3[@class='ms-standardheader']").InnerText.Trim();
            // 提取字段值,空值替换为Blank
            string fieldValue = tds[1].InnerText.Trim();
            if (string.IsNullOrEmpty(fieldValue)) fieldValue = "Blank";
            resultDict.Add(fieldName, fieldValue);
        }

        // 生成目标格式JSON
        string jsonResult = JsonConvert.SerializeObject(resultDict, Formatting.Indented);
        Console.WriteLine(jsonResult);

        // 插入数据库可直接遍历resultDict,使用SqlClient或者对应数据库驱动执行插入逻辑即可,和Python实现逻辑一致
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:24:04