wechat-article-image-downloader.user.js
· 8.0 KiB · JavaScript
Raw
// ==UserScript==
// @name 微信公众号文章图片批量下载
// @namespace local.wechat-article-image-downloader
// @version 1.0.0
// @description 批量下载微信公众号文章中的图片和 GIF,并按文章标题与序号命名。
// @match https://mp.weixin.qq.com/s/*
// @match https://mp.weixin.qq.com/s?*
// @run-at document-idle
// @grant GM_download
// @connect qpic.cn
// ==/UserScript==
(function () {
'use strict';
const PANEL_ID = 'wx-image-downloader-panel';
const DOWNLOAD_GAP_MS = 350;
const SOURCE_ATTRIBUTES = [
'data-croporisrc',
'data-src',
'data-original',
'data-lazy-src',
'src',
];
const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));
function articleRoot() {
return document.querySelector('#js_content') || document.querySelector('article') || document.body;
}
function articleTitle() {
const title = document.querySelector('#activity-name')?.textContent
|| document.querySelector('meta[property="og:title"]')?.content
|| document.title
|| '微信公众号文章';
return sanitizeFilename(title.trim().replace(/\s+/g, ' ')) || '微信公众号文章';
}
function sanitizeFilename(value) {
return value
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
.replace(/[. ]+$/g, '')
.slice(0, 100);
}
function getImageType(img, url) {
const params = new URL(url).searchParams;
const format = (params.get('wx_fmt') || img.dataset.type || '').toLowerCase();
if (format === 'jpg' || format === 'jpeg') return 'jpg';
if (format === 'png' || format === 'gif' || format === 'webp' || format === 'bmp') return format;
const extension = new URL(url).pathname.match(/\.([a-z\d]+)$/i)?.[1]?.toLowerCase();
if (extension === 'jpeg') return 'jpg';
if (['jpg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) return extension;
return 'jpg';
}
function normalizeImageUrl(rawUrl, img) {
if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return null;
let url;
try {
url = new URL(rawUrl, location.href);
} catch {
return null;
}
if (!/^https?:$/.test(url.protocol)) return null;
if (/mmbiz\.qpic\.cn$/i.test(url.hostname)) {
// /0 是微信图片常见的原图地址;/640 是文章正文中的缩放图地址。
url.pathname = url.pathname.replace(/\/640(?=\/|$)/, '/0');
}
const type = (url.searchParams.get('wx_fmt') || img.dataset.type || '').toLowerCase();
if (['gif', 'png', 'jpeg', 'jpg', 'webp'].includes(type)) {
url.searchParams.set('wx_fmt', type === 'jpg' ? 'jpeg' : type);
}
// 去掉微信页面给预览图添加的格式转换和懒加载标记,避免 GIF 被转成静态 WebP。
['tp', 'wxfrom', 'wx_lazy', 'wx_co'].forEach((key) => url.searchParams.delete(key));
url.hash = '';
return url.href;
}
function collectImages() {
const seen = new Set();
const images = [];
articleRoot().querySelectorAll('img').forEach((img) => {
let rawUrl = '';
for (const attribute of SOURCE_ATTRIBUTES) {
const candidate = img.getAttribute(attribute);
if (candidate && !candidate.startsWith('data:image/')) {
rawUrl = candidate;
break;
}
}
const url = normalizeImageUrl(rawUrl, img);
if (!url || seen.has(url)) return;
seen.add(url);
images.push({
url,
extension: getImageType(img, url),
});
});
return images;
}
function downloadOne(url, name) {
return new Promise((resolve, reject) => {
if (typeof GM_download !== 'function') {
reject(new Error('GM_download 不可用,请确认脚本管理器已启用此脚本。'));
return;
}
GM_download({
url,
name,
saveAs: false,
onload: resolve,
onerror: (error) => reject(new Error(error?.error || '下载失败')),
ontimeout: () => reject(new Error('请求超时')),
});
});
}
function addPanel() {
if (document.getElementById(PANEL_ID)) return;
const panel = document.createElement('section');
panel.id = PANEL_ID;
panel.innerHTML = `
<div class="wxid-head">
<strong>文章图片下载</strong>
<button type="button" class="wxid-close" aria-label="收起">−</button>
</div>
<div class="wxid-body">
<div class="wxid-count"></div>
<button type="button" class="wxid-download">下载全部图片 / GIF</button>
<div class="wxid-status" role="status">GIF 会保留为动态文件。</div>
</div>`;
const style = document.createElement('style');
style.textContent = `
#${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:250px;color:#202124;
background:#fff;border:1px solid #d9dde3;border-radius:10px;box-shadow:0 4px 18px #0002;
font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
#${PANEL_ID} .wxid-head{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;
border-bottom:1px solid #eee}
#${PANEL_ID} button{font:inherit;cursor:pointer}
#${PANEL_ID} .wxid-close{border:0;background:transparent;font-size:20px;line-height:1;color:#666}
#${PANEL_ID} .wxid-body{padding:11px 12px 12px}
#${PANEL_ID} .wxid-count{margin-bottom:9px;color:#555}
#${PANEL_ID} .wxid-download{width:100%;padding:8px;border:0;border-radius:6px;background:#07c160;color:white}
#${PANEL_ID} .wxid-download:disabled{cursor:wait;opacity:.65}
#${PANEL_ID} .wxid-status{min-height:20px;margin-top:8px;color:#777;font-size:12px}
#${PANEL_ID}.wxid-collapsed{width:auto}
#${PANEL_ID}.wxid-collapsed .wxid-body{display:none}`;
document.head.append(style);
document.body.append(panel);
const count = panel.querySelector('.wxid-count');
const status = panel.querySelector('.wxid-status');
const downloadButton = panel.querySelector('.wxid-download');
const refreshCount = () => {
const total = collectImages().length;
count.textContent = `找到 ${total} 张不重复的图片`;
downloadButton.disabled = total === 0;
if (total === 0) status.textContent = '暂未找到图片,请等待文章内容加载后重试。';
};
panel.querySelector('.wxid-close').addEventListener('click', () => {
panel.classList.toggle('wxid-collapsed');
panel.querySelector('.wxid-close').textContent = panel.classList.contains('wxid-collapsed') ? '+' : '−';
});
downloadButton.addEventListener('click', async () => {
const images = collectImages();
if (!images.length) return;
downloadButton.disabled = true;
let succeeded = 0;
let failed = 0;
const title = articleTitle();
for (let index = 0; index < images.length; index += 1) {
const image = images[index];
const number = String(index + 1).padStart(3, '0');
const filename = `${title}_${number}.${image.extension}`;
status.textContent = `正在下载 ${index + 1}/${images.length}:${filename}`;
try {
await downloadOne(image.url, filename);
succeeded += 1;
} catch (error) {
failed += 1;
console.warn('[微信文章图片下载]', filename, error);
}
if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS);
}
status.textContent = failed
? `完成:成功 ${succeeded} 张,失败 ${failed} 张。可查看控制台了解失败原因。`
: `下载完成:${succeeded} 张。`;
downloadButton.disabled = false;
});
refreshCount();
// 兼容微信文章图片延迟插入正文的情况。
const observer = new MutationObserver(refreshCount);
observer.observe(articleRoot(), { childList: true, subtree: true });
window.setTimeout(() => observer.disconnect(), 30000);
}
if (document.body) addPanel();
else document.addEventListener('DOMContentLoaded', addPanel, { once: true });
})();
| 1 | // ==UserScript== |
| 2 | // @name 微信公众号文章图片批量下载 |
| 3 | // @namespace local.wechat-article-image-downloader |
| 4 | // @version 1.0.0 |
| 5 | // @description 批量下载微信公众号文章中的图片和 GIF,并按文章标题与序号命名。 |
| 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 | // @connect qpic.cn |
| 11 | // ==/UserScript== |
| 12 | |
| 13 | (function () { |
| 14 | 'use strict'; |
| 15 | |
| 16 | const PANEL_ID = 'wx-image-downloader-panel'; |
| 17 | const DOWNLOAD_GAP_MS = 350; |
| 18 | const SOURCE_ATTRIBUTES = [ |
| 19 | 'data-croporisrc', |
| 20 | 'data-src', |
| 21 | 'data-original', |
| 22 | 'data-lazy-src', |
| 23 | 'src', |
| 24 | ]; |
| 25 | |
| 26 | const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); |
| 27 | |
| 28 | function articleRoot() { |
| 29 | return document.querySelector('#js_content') || document.querySelector('article') || document.body; |
| 30 | } |
| 31 | |
| 32 | function articleTitle() { |
| 33 | const title = document.querySelector('#activity-name')?.textContent |
| 34 | || document.querySelector('meta[property="og:title"]')?.content |
| 35 | || document.title |
| 36 | || '微信公众号文章'; |
| 37 | return sanitizeFilename(title.trim().replace(/\s+/g, ' ')) || '微信公众号文章'; |
| 38 | } |
| 39 | |
| 40 | function sanitizeFilename(value) { |
| 41 | return value |
| 42 | .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_') |
| 43 | .replace(/[. ]+$/g, '') |
| 44 | .slice(0, 100); |
| 45 | } |
| 46 | |
| 47 | function getImageType(img, url) { |
| 48 | const params = new URL(url).searchParams; |
| 49 | const format = (params.get('wx_fmt') || img.dataset.type || '').toLowerCase(); |
| 50 | if (format === 'jpg' || format === 'jpeg') return 'jpg'; |
| 51 | if (format === 'png' || format === 'gif' || format === 'webp' || format === 'bmp') return format; |
| 52 | |
| 53 | const extension = new URL(url).pathname.match(/\.([a-z\d]+)$/i)?.[1]?.toLowerCase(); |
| 54 | if (extension === 'jpeg') return 'jpg'; |
| 55 | if (['jpg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) return extension; |
| 56 | return 'jpg'; |
| 57 | } |
| 58 | |
| 59 | function normalizeImageUrl(rawUrl, img) { |
| 60 | if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return null; |
| 61 | |
| 62 | let url; |
| 63 | try { |
| 64 | url = new URL(rawUrl, location.href); |
| 65 | } catch { |
| 66 | return null; |
| 67 | } |
| 68 | |
| 69 | if (!/^https?:$/.test(url.protocol)) return null; |
| 70 | if (/mmbiz\.qpic\.cn$/i.test(url.hostname)) { |
| 71 | // /0 是微信图片常见的原图地址;/640 是文章正文中的缩放图地址。 |
| 72 | url.pathname = url.pathname.replace(/\/640(?=\/|$)/, '/0'); |
| 73 | } |
| 74 | |
| 75 | const type = (url.searchParams.get('wx_fmt') || img.dataset.type || '').toLowerCase(); |
| 76 | if (['gif', 'png', 'jpeg', 'jpg', 'webp'].includes(type)) { |
| 77 | url.searchParams.set('wx_fmt', type === 'jpg' ? 'jpeg' : type); |
| 78 | } |
| 79 | |
| 80 | // 去掉微信页面给预览图添加的格式转换和懒加载标记,避免 GIF 被转成静态 WebP。 |
| 81 | ['tp', 'wxfrom', 'wx_lazy', 'wx_co'].forEach((key) => url.searchParams.delete(key)); |
| 82 | url.hash = ''; |
| 83 | return url.href; |
| 84 | } |
| 85 | |
| 86 | function collectImages() { |
| 87 | const seen = new Set(); |
| 88 | const images = []; |
| 89 | |
| 90 | articleRoot().querySelectorAll('img').forEach((img) => { |
| 91 | let rawUrl = ''; |
| 92 | for (const attribute of SOURCE_ATTRIBUTES) { |
| 93 | const candidate = img.getAttribute(attribute); |
| 94 | if (candidate && !candidate.startsWith('data:image/')) { |
| 95 | rawUrl = candidate; |
| 96 | break; |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | const url = normalizeImageUrl(rawUrl, img); |
| 101 | if (!url || seen.has(url)) return; |
| 102 | seen.add(url); |
| 103 | |
| 104 | images.push({ |
| 105 | url, |
| 106 | extension: getImageType(img, url), |
| 107 | }); |
| 108 | }); |
| 109 | |
| 110 | return images; |
| 111 | } |
| 112 | |
| 113 | function downloadOne(url, name) { |
| 114 | return new Promise((resolve, reject) => { |
| 115 | if (typeof GM_download !== 'function') { |
| 116 | reject(new Error('GM_download 不可用,请确认脚本管理器已启用此脚本。')); |
| 117 | return; |
| 118 | } |
| 119 | |
| 120 | GM_download({ |
| 121 | url, |
| 122 | name, |
| 123 | saveAs: false, |
| 124 | onload: resolve, |
| 125 | onerror: (error) => reject(new Error(error?.error || '下载失败')), |
| 126 | ontimeout: () => reject(new Error('请求超时')), |
| 127 | }); |
| 128 | }); |
| 129 | } |
| 130 | |
| 131 | function addPanel() { |
| 132 | if (document.getElementById(PANEL_ID)) return; |
| 133 | |
| 134 | const panel = document.createElement('section'); |
| 135 | panel.id = PANEL_ID; |
| 136 | panel.innerHTML = ` |
| 137 | <div class="wxid-head"> |
| 138 | <strong>文章图片下载</strong> |
| 139 | <button type="button" class="wxid-close" aria-label="收起">−</button> |
| 140 | </div> |
| 141 | <div class="wxid-body"> |
| 142 | <div class="wxid-count"></div> |
| 143 | <button type="button" class="wxid-download">下载全部图片 / GIF</button> |
| 144 | <div class="wxid-status" role="status">GIF 会保留为动态文件。</div> |
| 145 | </div>`; |
| 146 | |
| 147 | const style = document.createElement('style'); |
| 148 | style.textContent = ` |
| 149 | #${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:250px;color:#202124; |
| 150 | background:#fff;border:1px solid #d9dde3;border-radius:10px;box-shadow:0 4px 18px #0002; |
| 151 | font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif} |
| 152 | #${PANEL_ID} .wxid-head{display:flex;align-items:center;justify-content:space-between;padding:10px 12px; |
| 153 | border-bottom:1px solid #eee} |
| 154 | #${PANEL_ID} button{font:inherit;cursor:pointer} |
| 155 | #${PANEL_ID} .wxid-close{border:0;background:transparent;font-size:20px;line-height:1;color:#666} |
| 156 | #${PANEL_ID} .wxid-body{padding:11px 12px 12px} |
| 157 | #${PANEL_ID} .wxid-count{margin-bottom:9px;color:#555} |
| 158 | #${PANEL_ID} .wxid-download{width:100%;padding:8px;border:0;border-radius:6px;background:#07c160;color:white} |
| 159 | #${PANEL_ID} .wxid-download:disabled{cursor:wait;opacity:.65} |
| 160 | #${PANEL_ID} .wxid-status{min-height:20px;margin-top:8px;color:#777;font-size:12px} |
| 161 | #${PANEL_ID}.wxid-collapsed{width:auto} |
| 162 | #${PANEL_ID}.wxid-collapsed .wxid-body{display:none}`; |
| 163 | document.head.append(style); |
| 164 | document.body.append(panel); |
| 165 | |
| 166 | const count = panel.querySelector('.wxid-count'); |
| 167 | const status = panel.querySelector('.wxid-status'); |
| 168 | const downloadButton = panel.querySelector('.wxid-download'); |
| 169 | |
| 170 | const refreshCount = () => { |
| 171 | const total = collectImages().length; |
| 172 | count.textContent = `找到 ${total} 张不重复的图片`; |
| 173 | downloadButton.disabled = total === 0; |
| 174 | if (total === 0) status.textContent = '暂未找到图片,请等待文章内容加载后重试。'; |
| 175 | }; |
| 176 | |
| 177 | panel.querySelector('.wxid-close').addEventListener('click', () => { |
| 178 | panel.classList.toggle('wxid-collapsed'); |
| 179 | panel.querySelector('.wxid-close').textContent = panel.classList.contains('wxid-collapsed') ? '+' : '−'; |
| 180 | }); |
| 181 | |
| 182 | downloadButton.addEventListener('click', async () => { |
| 183 | const images = collectImages(); |
| 184 | if (!images.length) return; |
| 185 | |
| 186 | downloadButton.disabled = true; |
| 187 | let succeeded = 0; |
| 188 | let failed = 0; |
| 189 | const title = articleTitle(); |
| 190 | |
| 191 | for (let index = 0; index < images.length; index += 1) { |
| 192 | const image = images[index]; |
| 193 | const number = String(index + 1).padStart(3, '0'); |
| 194 | const filename = `${title}_${number}.${image.extension}`; |
| 195 | status.textContent = `正在下载 ${index + 1}/${images.length}:${filename}`; |
| 196 | try { |
| 197 | await downloadOne(image.url, filename); |
| 198 | succeeded += 1; |
| 199 | } catch (error) { |
| 200 | failed += 1; |
| 201 | console.warn('[微信文章图片下载]', filename, error); |
| 202 | } |
| 203 | if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS); |
| 204 | } |
| 205 | |
| 206 | status.textContent = failed |
| 207 | ? `完成:成功 ${succeeded} 张,失败 ${failed} 张。可查看控制台了解失败原因。` |
| 208 | : `下载完成:${succeeded} 张。`; |
| 209 | downloadButton.disabled = false; |
| 210 | }); |
| 211 | |
| 212 | refreshCount(); |
| 213 | // 兼容微信文章图片延迟插入正文的情况。 |
| 214 | const observer = new MutationObserver(refreshCount); |
| 215 | observer.observe(articleRoot(), { childList: true, subtree: true }); |
| 216 | window.setTimeout(() => observer.disconnect(), 30000); |
| 217 | } |
| 218 | |
| 219 | if (document.body) addPanel(); |
| 220 | else document.addEventListener('DOMContentLoaded', addPanel, { once: true }); |
| 221 | })(); |
| 222 |