// ==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 = `
文章图片下载
GIF 会保留为动态文件。
`; 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 }); })();