【小技巧】如何保存邮件中的表格内容为图片
评论
收藏

【小技巧】如何保存邮件中的表格内容为图片

经验分享
阿蓝
2024-05-29 15:20·浏览量:429
阿蓝
发布于 2024-05-29 15:20429浏览

问题描述

客户经常需要从收到的邮件中提取表格内容,而邮件中的表格内容以 html 代码的格式写入,直接读取文件的文本内容,无法保持表格的样式,也不方便做数据的提取处理。

解决思路一

1. 通过【获取邮件】读取邮件内容,拿到 HTML正文,即 html_body;

2. 提取表格部分的代码,保存为本地 .html 的临时文件;

3. 打开本地 .html 文件,对表格部分进行截图,保存为本地图片文件

import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
from tempfile import NamedTemporaryFile

# 假设你的HTML字符串如下
html_string = 邮件.html_body

# 将HTML字符串写入临时文件
with NamedTemporaryFile('w', delete=False, suffix='.html') as tmp_file:
    tmp_file.write(html_string)
    tmp_file_path = tmp_file.name

# 设置Chrome选项
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920x1080")

# 初始化Chrome WebDriver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options)

# 打开临时HTML文件
driver.get(f"file:///{tmp_file_path}")

# 等待页面加载
driver.implicitly_wait(10)

# 找到表格元素
table = driver.find_element(By.TAG_NAME, 'table')

# 获取表格元素的位置和大小
location = table.location
size = table.size

# 对整个页面截图
screenshot_path = "full_screenshot.png"
driver.save_screenshot(screenshot_path)

# 打开截图并裁剪
image = Image.open(screenshot_path)
left = location['x']
top = location['y']
right = left + size['width']
bottom = top + size['height']

table_image = image.crop((left, top, right, bottom))
table_image.save("需要保存的图片路径.png")

# 关闭浏览器并删除临时文件
driver.quit()
os.remove(tmp_file_path)

拿到结果

解决思路二

1. 提取表格部分的代码,保存为列表,可支持写入 Excel 文件或数据表格;

from bs4 import BeautifulSoup
import openpyxl
from openpyxl import Workbook
from openpyxl.drawing.image import Image
import requests
from io import BytesIO

html_content = 邮件.html_body

# 使用 BeautifulSoup 解析 HTML 内容
soup = BeautifulSoup(html_content, 'html.parser')

# 提取表格内容
rows = soup.find('tbody').find_all('tr')

# 创建二维列表
table_data = []
for row in rows:
    row_data = []
    cells = row.find_all('td')
    for cell in cells:
        if cell.find('img'):
            row_data.append(cell.find('img')['src'])
        else:
            row_data.append(cell.get_text(strip=True))
    table_data.append(row_data)

# 创建一个新的工作簿
wb = Workbook()
ws = wb.active

# 将多维列表数据写入Excel工作表
for i, row in enumerate(table_data):
    for j, cell in enumerate(row):
        if "http" in cell:
            # 下载图片并插入单元格
            response = requests.get(cell)
            img_data = BytesIO(response.content)
            img = Image(img_data)
            ws.add_image(img, ws.cell(row=i + 1, column=j + 1).coordinate)
        else:
            ws.cell(row=i + 1, column=j + 1, value=cell)

# 保存工作簿为Excel文件
wb.save("需要保存的文件路径.xlsx")

2. 写入 Excel 文件后,可以使用影刀的区域截图指令对 Excel 进行截图。

(ps:个人觉得写入表格文件后,还需要进行行高列宽的调整,还有图片内容的单元格填充,再进行区域截图等等一系列操作下来,是不如解决思路一来得方便的。如果你的目的只是 Excel 文件,而不需要截图,那还是可以参考这个方案来处理。)


如果 Excel 指令截图不清晰怎么办,指路👉: https://www.yingdao.com/community/detaildiscuss?id=b11520cb-a43e-46a1-9ec0-fd293ca25fcb&tag=&from=userCenter&sort=createTime&page=1

收藏1
全部评论1
最新
发布评论
评论