// ==UserScript== // @name 微信公众号文章图片批量下载 // @namespace local.wechat-article-image-downloader // @version 1.2.0 // @description 将微信公众号文章和图文轮播中的图片及链接信息下载到标题文件夹。 // @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 discoveredImages = new Map(); 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(mediaNode, url) { const params = new URL(url).searchParams; const format = (params.get('wx_fmt') || mediaNode.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, mediaNode) { 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') || mediaNode.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.searchParams.sort(); url.hash = ''; return url.href; } function collectImages() { const root = articleRoot(); const mediaNodes = Array.from(root.querySelectorAll('img, .swiper_item[data-src]')); // 某些图文模式把轮播组件放在 #js_content 之外;只补充轮播容器,避免扫入头像等页面图片。 document.querySelectorAll('.swiper_item[data-src]').forEach((item) => { if (!root.contains(item)) mediaNodes.push(item); }); mediaNodes.forEach((mediaNode) => { let rawUrl = ''; if (mediaNode.matches('.swiper_item[data-src]')) { // 轮播容器的 data-src 通常是 /0 原图;子级 img.src 可能是 tp=webp 预览图。 rawUrl = mediaNode.getAttribute('data-src') || ''; } else { for (const attribute of SOURCE_ATTRIBUTES) { const candidate = mediaNode.getAttribute(attribute); if (candidate && !candidate.startsWith('data:image/')) { rawUrl = candidate; break; } } } const url = normalizeImageUrl(rawUrl, mediaNode); if (!url || discoveredImages.has(url)) return; discoveredImages.set(url, { url, extension: getImageType(mediaNode, url), }); }); return Array.from(discoveredImages.values()); } 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 createInfoFile(title, images, results) { const exportedAt = new Date().toLocaleString('zh-CN', { dateStyle: 'long', timeStyle: 'medium', }); const lines = [ `标题:${title}`, `文章链接:${location.href}`, `导出时间:${exportedAt}`, `图片总数:${images.length}`, '', '图片清单:', ]; results.forEach((result) => { lines.push(`- ${result.filename} [${result.success ? '下载成功' : '下载失败'}]`); lines.push(` 图片地址:${result.url}`); if (result.error) lines.push(` 失败原因:${result.error}`); }); return new Blob([`\uFEFF${lines.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }); } 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(); const folderName = title; const results = []; for (let index = 0; index < images.length; index += 1) { const image = images[index]; const number = String(index + 1).padStart(3, '0'); const filename = `${folderName}/${title}_${number}.${image.extension}`; status.textContent = `正在下载 ${index + 1}/${images.length}:${title}_${number}.${image.extension}`; try { await downloadOne(image.url, filename); succeeded += 1; results.push({ filename: `${title}_${number}.${image.extension}`, url: image.url, success: true }); } catch (error) { failed += 1; console.warn('[微信文章图片下载]', filename, error); results.push({ filename: `${title}_${number}.${image.extension}`, url: image.url, success: false, error: error.message, }); } if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS); } let infoSaved = false; try { status.textContent = '正在保存文章链接和图片清单…'; await downloadOne(createInfoFile(title, images, results), `${folderName}/info.txt`); infoSaved = true; } catch (error) { console.warn('[微信文章图片下载] info.txt', error); } status.textContent = failed ? `图片成功 ${succeeded} 张,失败 ${failed} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。` : `下载完成:${succeeded} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`; downloadButton.disabled = false; }); refreshCount(); // 兼容微信文章图片延迟插入正文的情况。 let refreshTimer; const observer = new MutationObserver((mutations) => { if (!mutations.some((mutation) => !panel.contains(mutation.target))) return; window.clearTimeout(refreshTimer); refreshTimer = window.setTimeout(refreshCount, 150); }); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-src', 'src'], }); window.setTimeout(() => observer.disconnect(), 30000); } if (document.body) addPanel(); else document.addEventListener('DOMContentLoaded', addPanel, { once: true }); })();