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

使用BeautifulSoup提取HTML写入Excel时遇openpyxl非法字符错误

解决openpyxl.utils.exceptions.IllegalCharacterError问题

这个错误的核心原因是你从HTML里提取的文本包含了Excel单元格不支持的特殊控制字符(比如ASCII 0-31区间里除了\t、\n、\r之外的字符,或者部分Unicode控制字符),和Python版本、库的版本无关,所以升级重装都没用,得从清理数据入手。

具体解决步骤:

  1. 添加文本清理函数
    写一个辅助函数,过滤掉所有Excel不允许的非法字符,示例代码:
import re

def clean_excel_text(text):
    if not text:
        return ""
    # 匹配并移除Excel禁用的控制字符
    illegal_pattern = re.compile(r'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]')
    cleaned_text = illegal_pattern.sub('', text)
    # 额外处理可能存在的Unicode换行分隔符
    cleaned_text = cleaned_text.replace('\u2028', ' ').replace('\u2029', ' ')
    return cleaned_text.strip()
  1. 在提取文本后调用清理函数
    把你原来提取文本的代码,比如:
extracted_content = soup.find("目标标签").get_text()

改成:

extracted_content = clean_excel_text(soup.find("目标标签").get_text())
  1. 批量处理时添加异常捕获
    因为要处理3万多个文件,建议在循环里加异常捕获,定位出错的文件,避免整个程序崩溃:
import os
from bs4 import BeautifulSoup
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

file_dir = "你的HTML文件目录"
file_list = [os.path.join(file_dir, f) for f in os.listdir(file_dir) if f.endswith(".html")]

for idx, file_path in enumerate(file_list, 1):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            soup = BeautifulSoup(f.read(), 'html.parser')
            # 提取文本并清理
            content = clean_excel_text(soup.find("你的目标选择器").get_text())
            # 写入Excel
            ws.cell(row=idx, column=1, value=content)
    except Exception as e:
        print(f"第{idx}个文件 {file_path} 处理失败: {str(e)}")
        continue

wb.save("结果文件.xlsx")

这样处理后,就能过滤掉导致错误的非法字符,顺利写入Excel了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:55:33