Última actividad 1792549450

批量下载微信公众号文章中的图片和 GIF,并按文章标题与序号命名。

Readme.md Sin formato

微信公众号文章图片批量下载

一个 Tampermonkey 用户脚本,用于在微信公众号文章页批量下载正文图片、GIF,以及“图文”模式左右滑动轮播中的图片。

安装

  1. 安装 Tampermonkey 浏览器扩展。
  2. 新建脚本,将 wechat-article-image-downloader.user.js 全部内容粘贴进去并保存。
  3. 打开 https://mp.weixin.qq.com/s/... 文章页,页面右下角会出现“文章图片下载”面板。
  4. 点击“下载全部图片 / GIF”。脚本会在浏览器下载目录下创建以文章标题命名的文件夹,图片和 info.txt 都放在该文件夹内。浏览器可能会询问是否允许此站点批量下载,请允许。
  5. 如果 Tampermonkey 提示文件扩展名未获准,在扩展设置中允许 txt、jpg、png、gif、webp、bmp 文件类型。

图片地址与文件名

普通文章图片按 data-croporisrc、data-src、data-original、data-lazy-src、src 的顺序读取地址。图文轮播模式会额外读取 .swiper_item[data-src];该容器地址优先于子级 <img src>,因为后者可能是 tp=webp 预览图。对 mmbiz.qpic.cn 地址,脚本会将路径中的 /640 改为微信常见的原图路径 /0,并清除 tp=webp 等页面预览参数;图片格式从 wx_fmt 或图片元素的 data-type 推断。因此 GIF 按 .gif 下载,不会被页面的 WebP 预览地址变成静态图。

文件名使用“文章标题_序号.扩展名”,例如 大肥鱼表情包_001.gif。重复地址只下载一次。页面动态加载或轮播切换后新发现的地址会加入本次图片列表。

每次批量下载会生成 info.txt,记录文章标题、当前文章链接、导出时间,以及每张图片的文件名、源地址和下载结果。文件夹和文件名会清理 Windows 不支持的字符。

使用边界

  • 页面里已经加载或写入 DOM 的正文图片和轮播项会被扫描;动态插入或轮播切换后新发现的图片会在面板计数刷新时纳入。
  • 微信 CDN 的地址规则可能变化;如果个别图片下载失败,可检查浏览器控制台和 Tampermonkey 的下载权限。
  • info.txt 通过 Tampermonkey 的 Blob 下载接口生成;请使用支持 Blob 下载的 Tampermonkey 版本(5.4.6226 或更新版本)。
  • 脚本处理文章正文中的 <img> 和 .swiper_item[data-src],不处理视频封面、CSS 背景图或文章内嵌的其他文件。若轮播采用虚拟列表,只将当前页放入 DOM,建议先左右浏览一次各页,让脚本发现其图片地址。
wechat-article-image-downloader.user.js Sin formato
1// ==UserScript==
2// @name 微信公众号文章图片批量下载
3// @namespace local.wechat-article-image-downloader
4// @version 1.2.1
5// @description 将微信公众号文章和图文轮播中的图片及链接信息下载到标题文件夹。
6// @match https://mp.weixin.qq.com/s/*
7// @match https://mp.weixin.qq.com/s?*
8// @run-at document-idle
9// @grant GM_download
10// @icon https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico
11// @connect qpic.cn
12// ==/UserScript==
13
14(function () {
15 'use strict';
16
17 const PANEL_ID = 'wx-image-downloader-panel';
18 const DOWNLOAD_GAP_MS = 350;
19 const SOURCE_ATTRIBUTES = [
20 'data-croporisrc',
21 'data-src',
22 'data-original',
23 'data-lazy-src',
24 'src',
25 ];
26 const discoveredImages = new Map();
27
28 const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));
29
30 function articleRoot() {
31 return document.querySelector('#js_content') || document.querySelector('article') || document.body;
32 }
33
34 function articleTitle() {
35 const title = document.querySelector('#activity-name')?.textContent
36 || document.querySelector('meta[property="og:title"]')?.content
37 || document.title
38 || '微信公众号文章';
39 return sanitizeFilename(title.trim().replace(/\s+/g, ' ')) || '微信公众号文章';
40 }
41
42 function sanitizeFilename(value) {
43 return value
44 .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
45 .replace(/[. ]+$/g, '')
46 .slice(0, 100);
47 }
48
49 function getImageType(mediaNode, url) {
50 const params = new URL(url).searchParams;
51 const format = (params.get('wx_fmt') || mediaNode.dataset.type || '').toLowerCase();
52 if (format === 'jpg' || format === 'jpeg') return 'jpg';
53 if (format === 'png' || format === 'gif' || format === 'webp' || format === 'bmp') return format;
54
55 const extension = new URL(url).pathname.match(/\.([a-z\d]+)$/i)?.[1]?.toLowerCase();
56 if (extension === 'jpeg') return 'jpg';
57 if (['jpg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) return extension;
58 return 'jpg';
59 }
60
61 function normalizeImageUrl(rawUrl, mediaNode) {
62 if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return null;
63
64 let url;
65 try {
66 url = new URL(rawUrl, location.href);
67 } catch {
68 return null;
69 }
70
71 if (!/^https?:$/.test(url.protocol)) return null;
72 if (/mmbiz\.qpic\.cn$/i.test(url.hostname)) {
73 // /0 是微信图片常见的原图地址;/640 是文章正文中的缩放图地址。
74 url.pathname = url.pathname.replace(/\/640(?=\/|$)/, '/0');
75 }
76
77 const type = (url.searchParams.get('wx_fmt') || mediaNode.dataset.type || '').toLowerCase();
78 if (['gif', 'png', 'jpeg', 'jpg', 'webp'].includes(type)) {
79 url.searchParams.set('wx_fmt', type === 'jpg' ? 'jpeg' : type);
80 }
81
82 // 去掉微信页面给预览图添加的格式转换和懒加载标记,避免 GIF 被转成静态 WebP。
83 ['tp', 'wxfrom', 'wx_lazy', 'wx_co'].forEach((key) => url.searchParams.delete(key));
84 // 不同节点可能以不同顺序排列相同的查询参数;排序后才能正确去重。
85 url.searchParams.sort();
86 url.hash = '';
87 return url.href;
88 }
89
90 function collectImages() {
91 const root = articleRoot();
92 const mediaNodes = Array.from(root.querySelectorAll('img, .swiper_item[data-src]'));
93
94 // 某些图文模式把轮播组件放在 #js_content 之外;只补充轮播容器,避免扫入头像等页面图片。
95 document.querySelectorAll('.swiper_item[data-src]').forEach((item) => {
96 if (!root.contains(item)) mediaNodes.push(item);
97 });
98
99 mediaNodes.forEach((mediaNode) => {
100 let rawUrl = '';
101 if (mediaNode.matches('.swiper_item[data-src]')) {
102 // 轮播容器的 data-src 通常是 /0 原图;子级 img.src 可能是 tp=webp 预览图。
103 rawUrl = mediaNode.getAttribute('data-src') || '';
104 } else {
105 for (const attribute of SOURCE_ATTRIBUTES) {
106 const candidate = mediaNode.getAttribute(attribute);
107 if (candidate && !candidate.startsWith('data:image/')) {
108 rawUrl = candidate;
109 break;
110 }
111 }
112 }
113
114 const url = normalizeImageUrl(rawUrl, mediaNode);
115 if (!url || discoveredImages.has(url)) return;
116
117 discoveredImages.set(url, {
118 url,
119 extension: getImageType(mediaNode, url),
120 });
121 });
122
123 return Array.from(discoveredImages.values());
124 }
125
126 function downloadOne(url, name) {
127 return new Promise((resolve, reject) => {
128 if (typeof GM_download !== 'function') {
129 reject(new Error('GM_download 不可用,请确认脚本管理器已启用此脚本。'));
130 return;
131 }
132
133 GM_download({
134 url,
135 name,
136 saveAs: false,
137 onload: resolve,
138 onerror: (error) => reject(new Error(error?.error || '下载失败')),
139 ontimeout: () => reject(new Error('请求超时')),
140 });
141 });
142 }
143
144 function createInfoFile(title, images, results) {
145 const exportedAt = new Date().toLocaleString('zh-CN', {
146 dateStyle: 'long',
147 timeStyle: 'medium',
148 });
149 const lines = [
150 `标题:${title}`,
151 `文章链接:${location.href}`,
152 `导出时间:${exportedAt}`,
153 `图片总数:${images.length}`,
154 '',
155 '图片清单:',
156 ];
157
158 results.forEach((result) => {
159 lines.push(`- ${result.filename} [${result.success ? '下载成功' : '下载失败'}]`);
160 lines.push(` 图片地址:${result.url}`);
161 if (result.error) lines.push(` 失败原因:${result.error}`);
162 });
163
164 return new Blob([`\uFEFF${lines.join('\n')}\n`], { type: 'text/plain;charset=utf-8' });
165 }
166
167 function addPanel() {
168 if (document.getElementById(PANEL_ID)) return;
169
170 const panel = document.createElement('section');
171 panel.id = PANEL_ID;
172 panel.innerHTML = `
173 <div class="wxid-head">
174 <strong>文章图片下载</strong>
175 <button type="button" class="wxid-close" aria-label="收起">−</button>
176 </div>
177 <div class="wxid-body">
178 <div class="wxid-count"></div>
179 <button type="button" class="wxid-download">下载全部图片 / GIF</button>
180 <div class="wxid-status" role="status">GIF 会保留为动态文件。</div>
181 </div>`;
182
183 const style = document.createElement('style');
184 style.textContent = `
185 #${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:250px;color:#202124;
186 background:#fff;border:1px solid #d9dde3;border-radius:10px;box-shadow:0 4px 18px #0002;
187 font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
188 #${PANEL_ID} .wxid-head{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;
189 border-bottom:1px solid #eee}
190 #${PANEL_ID} button{font:inherit;cursor:pointer}
191 #${PANEL_ID} .wxid-close{border:0;background:transparent;font-size:20px;line-height:1;color:#666}
192 #${PANEL_ID} .wxid-body{padding:11px 12px 12px}
193 #${PANEL_ID} .wxid-count{margin-bottom:9px;color:#555}
194 #${PANEL_ID} .wxid-download{width:100%;padding:8px;border:0;border-radius:6px;background:#07c160;color:white}
195 #${PANEL_ID} .wxid-download:disabled{cursor:wait;opacity:.65}
196 #${PANEL_ID} .wxid-status{min-height:20px;margin-top:8px;color:#777;font-size:12px}
197 #${PANEL_ID}.wxid-collapsed{width:auto}
198 #${PANEL_ID}.wxid-collapsed .wxid-body{display:none}`;
199 document.head.append(style);
200 document.body.append(panel);
201
202 const count = panel.querySelector('.wxid-count');
203 const status = panel.querySelector('.wxid-status');
204 const downloadButton = panel.querySelector('.wxid-download');
205
206 const refreshCount = () => {
207 const total = collectImages().length;
208 count.textContent = `找到 ${total} 张不重复的图片`;
209 downloadButton.disabled = total === 0;
210 if (total === 0) status.textContent = '暂未找到图片,请等待文章内容加载后重试。';
211 };
212
213 panel.querySelector('.wxid-close').addEventListener('click', () => {
214 panel.classList.toggle('wxid-collapsed');
215 panel.querySelector('.wxid-close').textContent = panel.classList.contains('wxid-collapsed') ? '+' : '−';
216 });
217
218 downloadButton.addEventListener('click', async () => {
219 const images = collectImages();
220 if (!images.length) return;
221
222 downloadButton.disabled = true;
223 let succeeded = 0;
224 let failed = 0;
225 const title = articleTitle();
226 const folderName = title;
227 const results = [];
228
229 for (let index = 0; index < images.length; index += 1) {
230 const image = images[index];
231 const number = String(index + 1).padStart(3, '0');
232 const filename = `${folderName}/${title}_${number}.${image.extension}`;
233 status.textContent = `正在下载 ${index + 1}/${images.length}:${title}_${number}.${image.extension}`;
234 try {
235 await downloadOne(image.url, filename);
236 succeeded += 1;
237 results.push({ filename: `${title}_${number}.${image.extension}`, url: image.url, success: true });
238 } catch (error) {
239 failed += 1;
240 console.warn('[微信文章图片下载]', filename, error);
241 results.push({
242 filename: `${title}_${number}.${image.extension}`,
243 url: image.url,
244 success: false,
245 error: error.message,
246 });
247 }
248 if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS);
249 }
250
251 let infoSaved = false;
252 try {
253 status.textContent = '正在保存文章链接和图片清单…';
254 await downloadOne(createInfoFile(title, images, results), `${folderName}/info.txt`);
255 infoSaved = true;
256 } catch (error) {
257 console.warn('[微信文章图片下载] info.txt', error);
258 }
259
260 status.textContent = failed
261 ? `图片成功 ${succeeded} 张,失败 ${failed} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`
262 : `下载完成:${succeeded} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`;
263 downloadButton.disabled = false;
264 });
265
266 refreshCount();
267 // 兼容微信文章图片延迟插入正文的情况。
268 let refreshTimer;
269 const observer = new MutationObserver((mutations) => {
270 if (!mutations.some((mutation) => !panel.contains(mutation.target))) return;
271 window.clearTimeout(refreshTimer);
272 refreshTimer = window.setTimeout(refreshCount, 150);
273 });
274 observer.observe(document.body, {
275 childList: true,
276 subtree: true,
277 attributes: true,
278 attributeFilter: ['data-src', 'src'],
279 });
280 window.setTimeout(() => observer.disconnect(), 30000);
281 }
282
283 if (document.body) addPanel();
284 else document.addEventListener('DOMContentLoaded', addPanel, { once: true });
285})();
286