在借助kimi智能助手中输入提示词:
你是一个Python编程专家,要完成一个网页爬取Python脚本的任务,具体步骤如下:
打开文件夹:E:6451
注意:图片体积较大,占用内存高,要将PDF文件中的图片分批次提取,而不是一次性提取所有图片
kim生成的Python源代码:
import os
# 定义文件夹路径
folder_path = 'E:\6451'
# 确保文件夹存在
if not os.path.exists(folder_path):
print(f"The folder {folder_path} does not exist.")
else:
for filename in os.listdir(folder_path):
pdf_path = os.path.join(folder_path, filename)
# 逐页提取图片
for page_number in range(len(doc)):
page = doc[page_number]
img_list = page.get_images(full=True)
# 分批次提取页面中的图片
for img_index, img in enumerate(img_list, start=1):
try:
xref = img[0]
info = doc.extract_image(xref)
image_bytes = info["image"]
# 为图片构造一个唯一的文件名
image_filename = f"{os.path.splitext(filename)[0]}_{page_number + 1}_img_{img_index}.png"
image_save_path = os.path.join(folder_path, image_filename)
# 保存图片
with open(image_save_path, "wb") as image_file:
image_file.write(image_bytes)
print(f"Image saved: {image_save_path}")
except Exception as e:
print(f"Error saving image from page {page_number + 1}: {e}")
# 释放内存
del page, img_list
doc.close
print(f"Finished extracting images from {filename}")
# 输出信息到屏幕
# 确保屏幕输出信息
input("按任意键退出...")
在vscode中运行Python程序,成功提取所有图片:
转载此文是出于传递更多信息目的。若来源标注错误或侵犯了您的合法权益,请与本站联系,我们将及时更正、删除、谢谢。
https://www.414w.com/read/414913.html