学习Python心得之用Python下载图片并生成PPT

工作中遇到一个需要将网页内的图片下载下来并生成ppt。

这个网址中的每个页面都可以利用右键保存的方式下载下来。

1、利用os模块生成桌面文件路径,并新建临时图片保存目录

# 桌面文件路径
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
desktop = winreg.QueryValueEx(key, "Desktop")[0]
# 新建临时图片存放文件夹
path_pic = f'{desktop}\\材料'
os.mkdir(path_pic)

2、利用requests模块下载图片,因为网址是类似http://www.123.com/images/2023/03/abc/abc_0000.jpeg的这种形式,单随着序号的增加,网址总长度不变,***—0010.jpeg或***—01000.jpeg这种后缀,所以用for i in range()和if循环生成下载需要的地址。

wj = input("输入文件名:")
a = int(input("输入幻灯片页数:"))
b = input("输入幻灯片名称:")
y = input('请输入两位数的月份:')
# 查找图片所在的网址
for i in range(a):
    if a >= 100 and i < 10 or a < 100 and i < 10:
        url = f'***/images/2023/{y}/{wj}/{wj}_000{str(i)}.jpeg'
    elif a >= 100 and i < 100 or a < 100:
        url = f'***/images/2023/{y}/{wj}/{wj}_00{str(i)}.jpeg'
    else:
        url = f'***/images/2023/{y}/{wj}/{wj}_0{str(i)}.jpeg'
    pic = requests.get(url=url, headers=headers).content
    img_path = f'{path_pic}/{str(i)}.jpg'
    # 下载
    with open(img_path, 'wb') as fp:
        fp.write(pic)

3、下载的图片在生成ppt时发生错误,发现是因为下载图片包含一个透明的图层既图片是RGBA格式的,需要转换成RGB格式

    # 图片格式转换
    img = Image.open(img_path)
    img = img.convert("RGB")
    img.save(img_path)

4、需要新建一个ppt,并设置好保存路径和ppt的比例!

# 设置ppt保存路径
os.chdir(desktop)
# 实例化 ppt 文档对象
prs = Presentation()
# 设置幻灯片尺寸,4:3
prs.slide_width = Inches(4)
prs.slide_height = Inches(3)

5、因为p、Python的奇怪的文件排序规则,需要对下载的图片进行排序,否则下载图片是乱序的,ppt看着就脑壳疼。

# 打开图片目录
p_list = os.listdir(path_pic)
# 图片按升序排列
p_list.sort(key=lambda x: int(x.split('.')[0]))

6、遍历图片目录并添加到ppt中

# 遍历图片目录
c = 0
while c < len(p_list):
    img_name1 = path_pic + '\\' + p_list[c]
    print(c, '添加幻灯片成功!!')
# 新建空白ppt页
    blank_slide = prs.slide_layouts[6]
    slide_1 = prs.slides.add_slide(blank_slide)
# 添加图片
    a = slide_1.shapes.add_picture(image_file=img_name1,
                                   left=Inches(0),
                                   top=Inches(0),
                                   width=Cm(10.16),
                                   height=Cm(7.62))
    c += 1

7、保存ppt并删除临时图片文件夹

# 保存 ppt
prs.save(f'{b}.pptx')
print(b, '下载完成!!!')
# 删除临时图片文件夹
shutil.rmtree(path_pic)

下面是完整的代码

import os  # 创建文件夹
import time  # 程序暂停
import requests   # 图片下载
from pptx.util import Inches, Cm   # 幻灯片添加
from pptx import Presentation   # 幻灯片添加
from PIL import Image   # 图片格式转换
import shutil   # 清空文件夹
import winreg   # 查找桌面文件夹


# 模拟浏览器
headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Apple'
                   'WebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
}
# 桌面文件路径
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
desktop = winreg.QueryValueEx(key, "Desktop")[0]
# 输入下载的参数
wj = input("输入文件名:")
a = int(input("输入幻灯片页数:"))
b = input("输入幻灯片名称:")
y = input('请输入两位数的月份:')
# 新建临时图片存放文件夹
path_pic = f'{desktop}\\材料'
os.mkdir(path_pic)

# 查找图片所在的网址
for i in range(a):
    if a >= 100 and i < 10 or a < 100 and i < 10:
        url = f'***/images/2023/{y}/{wj}/{wj}_000{str(i)}.jpeg'
    elif a >= 100 and i < 100 or a < 100:
        url = f'***/images/2023/{y}/{wj}/{wj}_00{str(i)}.jpeg'
    else:
        url = f'***/images/2023/{y}/{wj}/{wj}_0{str(i)}.jpeg'
    pic = requests.get(url=url, headers=headers).content
    img_path = f'{path_pic}/{str(i)}.jpg'
    # 下载
    with open(img_path, 'wb') as fp:
        fp.write(pic)
    # 图片格式转换
    img = Image.open(img_path)
    img = img.convert("RGB")
    img.save(img_path)
    print(i, '下载成功!')
    # 程序暂停
    time.sleep(2)

# 设置ppt保存路径
os.chdir(desktop)
# 实例化 ppt 文档对象
prs = Presentation()
# 设置幻灯片尺寸,4:3
prs.slide_width = Inches(4)
prs.slide_height = Inches(3)

# 打开图片目录
p_list = os.listdir(path_pic)
# 图片按升序排列
p_list.sort(key=lambda x: int(x.split('.')[0]))

# 遍历图片目录
c = 0
while c < len(p_list):
    img_name1 = path_pic + '\\' + p_list[c]
    print(c, '添加幻灯片成功!!')
# 新建空白ppt页
    blank_slide = prs.slide_layouts[6]
    slide_1 = prs.slides.add_slide(blank_slide)
# 添加图片
    a = slide_1.shapes.add_picture(image_file=img_name1,
                                   left=Inches(0),
                                   top=Inches(0),
                                   width=Cm(10.16),
                                   height=Cm(7.62))
    c += 1
# 保存 ppt
prs.save(f'{b}.pptx')
print(b, '下载完成!!!')
# 删除临时图片文件夹
shutil.rmtree(path_pic)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值