我的目标是抓取 html 数据,包括排序信息和 WEBP 图像并保存到 Excel 工作表。
WEBP 格式的图像无法直接插入到 Excel 工作表中。唯一的方法是先将 WEBP 转换为 PNG 或 JPG。但是,使用批量图像转换图像、保存到 PC 硬盘以及将保存的 PNG 从本地 PC 插入 Excel 需要时间来处理。
有什么方法可以将WEBP图片转为PNG并直接插入excel吗
#以下部分代码
url = "https://down-aka-tw.img.susercontent.com/tw-11134207-7qul7-lilu03jxchpw3d_tn.webp"
response = requests.get(url)
img_data = response.content
img_png = Image.open(BytesIO(requests.get(url).content)).convert("RGB") #from PIL import Image as pImage
img_png.save("C:\\temp\\image.png")
img = oImage('C:\\temp\\image.png') #from openpyxl.drawing.image import Image as oImage
wb = Workbook()
ws = wb.active
# insert images
ws.add_image(img, 'A1')
wb.save("C:\\temp\\export.xlsx")
wb.close()
我确实尝试将转换后的二进制 img_png 插入 Excel 工作表,但失败了。不过下载 URL WEBP,转换为 PNG 然后保存到 PC 是可行的。
img_png 可以是 print() 或 show()。如果将img_png插入到Excel中,则无法接受。所以我将 PNG 保存到 image.png 文件并使用 openpyxl(oImage) 打开图像。 img可以插入Excel。
有没有什么方法可以将WEBP图片转换为PNG并直接插入excel而不需要在插入Excel之前保存在本地
from io import BytesIO
from openpyxl.drawing.image import Image as oImage
import requests
from PIL import Image as Image
from openpyxl import Workbook
### Get image from URL
url = "https://down-aka-tw.img.susercontent.com/tw-11134207-7qul7-lilu03jxchpw3d_tn.webp"
response = requests.get(url)
img_data = response.content
img_png = Image.open(BytesIO(requests.get(url).content)).convert("RGB") #from PIL import Image as pImage
# img_png.save("C:\\temp\\image.png")
# img = oImage('C:\\temp\\image.png') #from openpyxl.drawing.image import Image as oImage
### Create Workbook and Sheet
wb = Workbook()
ws = wb.active
# insert images
img_stream = BytesIO()
img_png.save(img_stream, format='PNG')
img_openpyxl = oImage(img_stream)
### Add Image to sheet
ws.add_image(img_openpyxl, 'A1')
wb.save("export.xlsx")
# wb.close() # This line does nothing in your code.