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

使用Python+BeautifulSoup解析全量收件箱HTML表格导出CSV遇阻求助

修改后可直接运行的完整代码

import imaplib
import csv
from email.parser import BytesParser
from email.policy import default
from bs4 import BeautifulSoup

USER = 'USERNAME' 
PASSWORD ='PASSWORD' 
MAIL_SERVER = 'MAILSERVER'

# 存储所有表格数据
all_rows = []
# 标记表头是否已写入
header_written = False

# 连接邮箱
mail = imaplib.IMAP4_SSL(MAIL_SERVER)
mail.login(USER, PASSWORD)
mail.select('inbox')

# 搜索收件箱所有邮件的UID
result, data = mail.uid('search', None, "ALL")
all_email_uids = data[0].split()

# 遍历所有邮件
for uid in all_email_uids:
    try:
        # 拉取单封邮件原始内容
        result, data = mail.uid('fetch', uid, '(RFC822)')
        raw_email = data[0][1]
        email_message = BytesParser(policy=default).parsebytes(raw_email)
        
        # 提取HTML正文
        simplest = email_message.get_body(preferencelist=('html'))
        htmlcontent = simplest.get_content()
        
        # 解析HTML表格
        soup = BeautifulSoup(htmlcontent, 'html.parser')
        table = soup.find("table")
        if not table:
            continue
        
        # 提取当前邮件表格行数据
        current_rows = []
        for table_row in table.findAll('tr'):
            columns = table_row.findAll('td')
            output_row = []
            for column in columns:
                text = column.text.replace('\n', '').replace('\xa0', '').strip()
                output_row.append(text)
            if any(output_row): # 过滤空行
                current_rows.append(output_row)
        
        if not current_rows:
            continue
            
        # 仅首次写入表头
        if not header_written:
            all_rows.append(current_rows[0])
            header_written = True
        # 追加当前邮件的表格数据(跳过表头行)
        all_rows.extend(current_rows[1:])
    except Exception as e:
        print(f"处理uid为{uid}的邮件时出错,已跳过,错误信息:{str(e)}")
        continue

# 统一写入CSV文件
with open('output.csv', 'w', encoding='utf-8-sig', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(all_rows)

# 关闭邮箱连接
mail.logout()

关键调整说明

  • 补充导入了缺失的csv模块,解决原代码调用csv.writer报错的问题
  • 原代码仅提取最新一封邮件的UID,现在改为获取所有邮件UID后循环遍历处理
  • 新增异常捕获逻辑,遇到格式不符合要求的邮件会直接跳过,不会中断整个遍历流程
  • 统一管理所有表格数据,表头仅写入一次,避免重复出现表头行
  • CSV写入新增encoding='utf-8-sig'参数,避免打开CSV时中文乱码,newline=''参数避免Windows系统下出现多余空行
  • 新增邮箱连接退出逻辑,避免连接残留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:21:00