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