如何通过控制台脚本自动保存指定类名的图片?
Hey there! Since you already have the array of image src URLs from the browser console, let’s go through a few practical, reliable ways to save all those images automatically—depending on your comfort with code and the number of images you’re dealing with.
Option 1: Browser Console Script (Quick & No Setup)
If you just need to download a moderate number of images and don’t want to leave the browser, you can run this script directly in the console. It uses fetch to get the image as a blob, then creates a hidden download link for each one.
// Replace this with your actual array of image URLs const imageUrls = [ "https://example.com/image1.jpg", "https://example.com/image2.png", // ... add all your URLs here ]; async function batchDownloadImages(urls) { for (const [index, url] of urls.entries()) { try { // Fetch the image as a blob const response = await fetch(url); if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`); const blob = await response.blob(); // Create a temporary download link const downloadUrl = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = downloadUrl; // Use the original filename from the URL, or a fallback const fileName = url.split("/").pop() || `image-${index + 1}.${blob.type.split("/")[1]}`; link.download = fileName; // Trigger the download document.body.appendChild(link); link.click(); // Clean up document.body.removeChild(link); URL.revokeObjectURL(downloadUrl); // Add a small delay to avoid overwhelming the browser/server await new Promise(resolve => setTimeout(resolve, 1000)); } catch (err) { console.error(`Failed to download ${url}:`, err); } } } // Start the download process batchDownloadImages(imageUrls);
Notes for this method:
- Your browser might block multiple downloads at first—look for a prompt at the top of the window and allow pop-ups/downloads for the site.
- If you run into CORS errors, it means the site doesn’t allow cross-origin requests from the browser. In that case, switch to the Node.js method below.
Option 2: Node.js Script (More Stable for Large Batches)
For a large number of images, a Node.js script is more reliable—it runs locally on your computer, avoids browser limits, and lets you handle errors more gracefully. Here’s how to set it up:
Initialize a Node.js project (if you don’t have one already):
npm init -yInstall required packages: We’ll use
axiosfor fetching images andfs-extrato handle file system operations safely.npm install axios fs-extraCreate a script file (e.g.,
download-images.js) with this code:const axios = require("axios"); const fs = require("fs-extra"); const path = require("path"); // Your array of image URLs const imageUrls = [ "https://example.com/image1.jpg", "https://example.com/image2.png", // ... add all URLs here ]; // Directory where images will be saved (creates it if it doesn't exist) const saveDirectory = path.join(__dirname, "downloaded-images"); fs.ensureDirSync(saveDirectory); async function downloadSingleImage(url, savePath) { try { const response = await axios({ url: url, method: "GET", responseType: "stream", // Add a user-agent to mimic a browser (avoids some anti-scraping blocks) headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } }); const writer = fs.createWriteStream(savePath); response.data.pipe(writer); return new Promise((resolve, reject) => { writer.on("finish", resolve); writer.on("error", reject); }); } catch (err) { console.error(`Failed to download ${url}:`, err.message); throw err; } } async function batchDownload() { for (const [index, url] of imageUrls.entries()) { const fileName = url.split("/").pop() || `image-${index + 1}.jpg`; const savePath = path.join(saveDirectory, fileName); try { await downloadSingleImage(url, savePath); console.log(`✅ Saved: ${fileName}`); // Delay to avoid hitting server rate limits await new Promise(resolve => setTimeout(resolve, 1000)); } catch (err) { console.log(`❌ Skipped: ${fileName}`); } } console.log("\nBatch download complete!"); } // Start the process batchDownload();Run the script:
node download-images.js
Notes for this method:
- If the site has strict rate limits, increase the delay (
setTimeoutvalue) to avoid being blocked. - You can adjust the
User-Agentheader to match your actual browser’s user-agent string (find it vianavigator.userAgentin the browser console).
Option 3: Browser Extension (No Code Needed)
If you prefer not to write any code, use a dedicated download extension like DownThemAll! (available for Firefox and Chrome). Here’s how:
- Install the extension, then open its interface.
- Choose the "Import URLs" option and paste your entire array of image URLs (you can copy it directly from the console).
- Set your preferred save location and start the batch download.
内容的提问来源于stack exchange,提问作者Rosaria Vizzini

