据说这样子的代码更美观耐看。下面代码是针对固定网站的硬编码,不通用。
第一步下载图片
import os
import requests
from requests.exceptions import RequestException
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
def create_folder(folder_name):
"""创建文件夹,如果文件夹已存在则不执行任何操作"""
if not os.path.exists(folder_name):
os.makedirs(folder_name)
def download_image(url, save_path):
"""下载图片并保存到指定路径,同时附带headers"""
try:
response = requests.get(url, stream=True)
response.raise_for_status() # 如果请求失败,抛出HTTPError异常
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
except RequestException as e:
print(f"请求图片时发生错误: {e}")
except Exception as e:
print(f"保存图片时发生错误: {e}")
# 示例用法
driver = webdriver.Edge()
driver.maximize_window()
sh = [117009, 117023, 117067, 117109, 117184]
ljs = []
for s in sh:
lj = f'http://www.wujiangtong.com/FZG/webPage/FZG_Book_Pic.aspx?id={s}'
ljs.append(lj)
for link in ljs:
print('\n', link)
driver.get(link)
sleep(3)
bt = driver.title
imagefolder = f"d:/a/{sh[ljs.index(link)]}{bt}" # 图片文件夹名
create_folder(image_folder) # 创建图片文件夹
n = len(driver.find_elements(By.XPATH, '//*[@id="fb7-slider"]/li'))
for i in range(1, n + 1):
img = f'http://wjtimages.wjhistory.com/wjt/book/人物/{bt}/color/{i}.jpg@!wjt_book-v'
print(img)
save_path = os.path.join(imagefolder, f"image{str(i).zfill(3)}.jpg")
download_image(img, save_path)
driver.quit()
第二步文件夹下的子文件夹里的jpg合并为pdf
import os
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
def merge_images_to_pdf(image_dir, pdf_dir):
确保PDF目录存在
if not os.path.exists(pdf_dir):
os.makedirs(pdf_dir)
# 遍历图片目录中的所有文件和子目录
for root, dirs, files in os.walk(image_dir):
# 过滤出图片文件(这里假设图片是.jpg或.png格式)
image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.gif'))]
# 如果当前目录有图片文件
if image_files:
# 构建相对于源目录的相对路径
rel_path = os.path.relpath(root, image_dir)
# 构建PDF文件的路径
# pdf_path = os.path.join(pdf_dir, rel_path)
pdf_path = pdf_dir
# 如果PDF目录的相应子目录不存在,则创建它
if not os.path.exists(pdf_path):
os.makedirs(pdf_path)
# 构建PDF文件的完整路径和名称(假设与目录名称相同,但扩展名为.pdf)
pdf_file_name = os.path.join(pdf_path, os.path.basename(root) + '.pdf')
# 创建PDF文件并添加图片
c = canvas.Canvas(pdf_file_name, pagesize=letter)
image_width, image_height = letter
for image_file in image_files:
image_path = os.path.join(root, image_file)
c.drawImage(image_path, 0, 0, width=image_width, height=image_height)
c.showPage() # 开始新页面以放置下一张图片
c.save() # 保存PDF文件
使用示例
source_dir = 'd:/a' # 源目录,包含图片和子目录
destination_pdf_dir = 'd:/b' # 目标PDF目录
merge_images_to_pdf(source_dir, destination_pdf_dir)
|