如何将提取的表格数据导出为CSV、Excel或JSON格式?

解读

面试官问“提取的表格数据”如何落地,核心想验证三件事:

  1. 你是否真用 Beautiful Soup 把 <table> 结构拆干净(行、列、表头、合并单元格、残缺标签处理);
  2. 你是否熟悉国内主流数据交付格式(CSV 最轻、Excel 最通用、JSON 最方便前后端对接);
  3. 你是否能在“内存占用、编码、特殊字符、日期、数字精度”这些坑上给出工程级方案,而不是跑通 demo 就完事。
    回答时先展示“拆解→清洗→序列化→落地”四步闭环,再针对三种格式分别给出“一行代码”和“生产级”两套答案,体现你既懂敏捷又懂落地。

知识点

  1. Beautiful Soup 的表格解析 API:
    • soup.find('table') / soup.select('table.data') 定位;
    • thead.find_all('th') 拿表头;
    • tbody.find_all('tr') 迭代行;
    • row.find_all(['td','th']) 拿单元格;
    • cell.get_text(strip=True) 去空白;
    • cell.has_attr('rowspan')/colspan 处理合并单元格。
  2. Python 标准库与第三方库:
    • csv 模块:DictWriter、指定 newline=''、utf-8-sig 防 Excel 乱码;
    • pandas:DataFrame.to_csv/to_excel/to_json,自动对齐行列;
    • openpyxl 或 xlsxwriter:写 .xlsx,支持样式、冻结窗格、筛选;
    • json 模块:ensure_ascii=False 保留中文,indent=2 可读性。
  3. 国内常见坑:
    • Windows 双击打开 CSV 默认 GBK,需 utf-8-sig BOM 头;
    • Excel 对 15 位以上数字精度丢失,需前置 \t 或写成 ="123456789012345";
    • 合并单元格导致行长度不一致,需补空字符串;
    • 爬虫跑在 Linux 容器,写文件前先 os.makedirs('data', exist_ok=True);
    • 大表内存占用,pandas 用 chunksize 或 openpyxl write_only=True。

答案

下面给出“最小可运行”+“生产级”两段代码,面试官让你写伪代码也能脱口而出。

  1. 最小可运行(demo 场景,10 行以内)
import requests, csv, json, pandas as pd
from bs4 import BeautifulSoup

url = 'http://example.com/table.html'
soup = BeautifulSoup(requests.get(url).content, 'lxml')
table = soup.find('table')

# 解析
rows = [[td.get_text(strip=True) for td in tr.find_all(['td','th'])]
        for tr in table.find_all('tr')]
header, body = rows[0], rows[1:]

# CSV
with open('out.csv', 'w', newline='', encoding='utf-8-sig') as f:
    csv.writer(f).writerows([header] + body)

# Excel
pd.DataFrame(body, columns=header).to_excel('out.xlsx', index=False)

# JSON
json.dump([dict(zip(header, row)) for row in body],
          open('out.json', 'w', encoding='utf-8'),
          ensure_ascii=False, indent=2)
  1. 生产级(考虑合并单元格、大文件、中文、数字精度、日志)
import os, csv, json, logging, pandas as pd
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl.utils import get_column_letter

def parse_merged_table(table):
    """返回 List[Dict],自动补全 rowspan/colspan"""
    from collections import defaultdict
    cells = defaultdict(lambda: '')  # (row, col) -> text
    row_idx = 0
    for tr in table.select('tr'):
        col_idx = 0
        for td in tr.find_all(['td','th']):
            while cells[(row_idx, col_idx)]:  # 跳过被合并占位的格子
                col_idx += 1
            text = td.get_text(strip=True)
            rowspan = int(td.get('rowspan', 1))
            colspan = int(td.get('colspan', 1))
            for r in range(rowspan):
                for c in range(colspan):
                    cells[(row_idx + r, col_idx + c)] = text
            col_idx += colspan
        row_idx += 1
    # 转 DataFrame
    df = pd.DataFrame.from_dict(cells, orient='index').unstack().fillna('')
    df.index.name = 'row'; df.columns.name = 'col'
    return df.reset_index(drop=True)

def export_triple(df, basename='table'):
    os.makedirs('output', exist_ok=True)
    # CSV
    csv_path = f'output/{basename}.csv'
    df.to_csv(csv_path, index=False, encoding='utf-8-sig')
    # Excel
    xlsx_path = f'output/{basename}.xlsx'
    df.to_excel(xlsx_path, index=False, engine='openpyxl')
    # JSON
    json_path = f'output/{basename}.json'
    df.to_json(json_path, force_ascii=False, orient='records', indent=2)
    logging.info('triple export done: %s %s %s', csv_path, xlsx_path, json_path)

# 使用
html = open('page.html', encoding='utf-8').read()
soup = BeautifulSoup(html, 'lxml')
table = soup.select_one('table.data')
df = parse_merged_table(table)
export_triple(df, 'stock_list')   # 国内习惯用中文文件名也可

亮点:

  • 合并单元格用二维占位字典,避免错位;
  • 统一走 pandas DataFrame,后续可直接 df.to_sql / df.to_parquet 进数仓;
  • 编码、BOM、数字精度、日志、路径隔离一次到位,可直接上线 Airflow/调度平台。

拓展思考

  1. 如果页面是异步渲染(React、Vue),Beautiful Soup 只能拿到骨架,需要先用 Playwright/Pyppeteer 拿完整 HTML,再走同样解析流程;
  2. 国内监管要求数据留痕,可在导出 Excel 时同步写入隐藏工作表记录“爬取时间、URL、MD5”,方便审计;
  3. 大表(>100M)场景,pandas 会爆内存,可改用“流式 CSV”——csv.writer 逐行写入,Excel 用 xlsxwriter 的 constant_memory=True,JSON 用 orjson 的 iterable_dumps;
  4. 若表格跨页(分页组件),先把所有分页拼成一份 DataFrame 再导出,避免下游收到“断表”;
  5. 交付给财务同事时,Excel 模板往往带样式、公式、数据验证,可预置 openpyxl 模板文件,解析完后仅替换数据区,保持样式不变,提升专业度。