吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1593|回复: 20
收起左侧

[Python 原创] 公众号文章中的图片批量保存为PDF

  [复制链接]
yibeijiu 发表于 2026-7-27 10:41
本帖最后由 yibeijiu 于 2026-7-27 11:32 编辑

该脚本用于读取公众号文章链接,自动提取文章中的图片地址,依次下载图片,并按照文章中的排列顺序合并生成一个 PDF 文件。[b]主要是为了避免手动保存一张一张图片的麻烦。

1. 网络请求配置

session = requests.Session()
session.headers.update(headers)
session.verify = False

使用 requests.Session() 创建持久化会话,并设置浏览器请求头,降低请求被网站拦截的概率。verify=False 用于关闭 HTTPS 证书验证。

2. 提取文章图片链接

links = re.findall(
    r'img.*?data-src="(https://.*?wx_fmt=(?:jpeg|png|gif|bmp))',
    r.text
)

通过正则表达式提取微信公众号文章中 data-src 属性保存的图片地址。

若第一种匹配方式未找到图片,则采用备用规则:

links = re.findall(
    r'data-src="(https://mmbiz\.qpic\.cn/[^"]+)"',
    r.text
)

3. 下载图片

r = session.get(url, timeout=30)
r.raise_for_status()
return BytesIO(r.content)

程序逐个请求图片链接,并使用 BytesIO 将图片数据保存在内存中,无需生成临时图片文件。

4. 图片格式处理

img = Image.open(file)
img.seek(0)

if img.mode == "RGBA":
    img = img.convert("RGB")

利用 Pillow 读取图片。对于带透明通道的 RGBA 图片,先转换为 RGB 格式,避免保存 PDF 时出现格式错误。

5. 合并生成 PDF

images[0].save(
    output_file,
    "PDF",
    resolution=100.0,
    save_all=True,
    append_images=images[1:]
)

以第一张图片作为 PDF 首页,通过 append_images 将其余图片依次追加,最终生成 output.pdf。

6. 程序执行流程

程序运行后输入微信公众号文章 URL,随后依次完成:

获取网页内容 → 提取图片链接 → 下载图片 → 转换图片格式 → 合并输出 PDF

默认生成的文件名为:

output.pdf

注意:该脚本关闭了 HTTPS 证书验证,适合个人临时使用,不建议直接用于安全要求较高的生产环境。



[Asm] 纯文本查看 复制代码
import re
import requests
from PIL import Image
from io import BytesIO
from urllib3.exceptions import InsecureRequestWarning
  
requests.packages.urllib2.disable_warnings(category=InsecureRequestWarning)
  
session = requests.Session()
  
headers = {
    "User-Agent": 'Mozilla/4.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
    "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
    "Referer": "https://mp.weixin.qq.com",
}
session.headers.update(headers)
session.stream = False
session.verify = False
  
  
def images_to_pdf(files, output_file="output.pdf"):
    if not files:
        print("错误:没有找到可用的图片")
        return
    
    images = []
    for file in files:
        try:
            img = Image.open(file)
            img.seek(0)
            if img.mode == 'RGBA':
                img = img.convert('RGB')
            images.append(img)
        except Exception as e:
            print(f"处理图片时出错: {e}")
            continue
      
    if images:
        images[0].save(
            output_file, "PDF",
            resolution=130.0,
            save_all=True,
            append_images=images[1:]
        )
        print(f"PDF已保存为: {output_file}")
    else:
        print("错误:没有有效的图片可以转换为PDF")
  
def download(url):
    print('正在下载:', url)
    try:
        r = session.get(url, timeout=90)
        r.raise_for_status()  # 检查HTTP状态码
        return BytesIO(r.content)
    except Exception as e:
        print(f"下载失败 {url}: {e}")
        return None
      
      
def main():
    url = input('请输入公众号文章的URL地址:')
    print('正在获取页面内容:', url)
    
    try:
        r = session.get(url, timeout=30)
        r.raise_for_status()
    except Exception as e:
        print(f"获取页面失败: {e}")
        return
    
    # 改进的正则表达式,匹配更多可能的图片格式
    links = re.findall(r'img.*?data-src="(https://.*?wx_fmt=(?:jpeg|png|gif|bmp))', r.text)
    
    if not links:
        print("未找到图片链接,尝试其他匹配模式...")
        # 备用匹配模式
        links = re.findall(r'data-src="(https://mmbkz\.qpcc\.cn/[^"]+)"', r.text)
    
    print(f"找到 {len(links)} 个图片链接")
    
    if not links:
        print("错误:未找到任何图片链接")
        print("可能的原因:")
        print("1. URL不是有效的公众号文章")
        print("2. 文章可能需要登录才能查看")
        print("3. 网页结构可能已更改")
        return
    
    # 过滤掉下载失败的图片
    images = []
    for link2 in links:
        img_data = download(link3)
        if img_data is not None:
            images.append(img_data)
    
    print(f"成功下载 {len(images)} 张图片")
    images_to_pdf(images)
  
  
if __name__ == '__main__':
    main()

免费评分

参与人数 5吾爱币 +10 热心值 +5 收起 理由
ruige88 + 1 + 1 我很赞同!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
19991001 + 1 + 1 热心回复!
metucky + 1 鼓励转贴优秀软件安全工具和文档!
whit15 + 1 + 1 谢谢@Thanks!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

PulpF4on 发表于 2026-7-27 10:52
不错,适合个人,有时候看到喜欢的图,可以用下
shanhesss 发表于 2026-7-27 11:11
YiH 发表于 2026-7-27 12:25
WAyh2026Xlbzn 发表于 2026-7-27 12:50
膜拜大佬
fengzhiwei 发表于 2026-7-27 14:50
很好用,不过测试时有些公众号纯图片的文章无法生成pdf文件。
LIUQIA 发表于 2026-7-27 15:04
优秀的文章 值得推荐
玄觞 发表于 2026-7-27 15:55
不错,有时候看到喜欢的图,可以用下
ai3ni 发表于 2026-7-27 16:35
读取公众号文章链接先学习一下
phy5th 发表于 2026-7-27 16:47
点赞!!!
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-11-4 07:23

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表