Created
October 12, 2023 22:41
-
-
Save martylouis/e7689a5da335c2ed768f88cfec8b2566 to your computer and use it in GitHub Desktop.
Save all images on a website locally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function selectDirectory() { | |
try { | |
const handle = await window.showDirectoryPicker(); | |
return handle; | |
} catch (error) { | |
console.error("Error:", error); | |
} | |
} | |
function downloadImages(url, saveDirectoryHandle) { | |
fetch(url) | |
.then(response => response.text()) | |
.then(html => { | |
const parser = new DOMParser(); | |
const doc = parser.parseFromString(html, "text/html"); | |
const imageTags = doc.querySelectorAll("img"); | |
imageTags.forEach(async (imageTag, index) => { | |
const imageUrl = imageTag.src; | |
const absoluteImageUrl = new URL(imageUrl, url).href; | |
const imageFileName = `${index + 1}.jpg`; | |
try { | |
const fileHandle = await saveDirectoryHandle.getFileHandle(imageFileName, { create: true }); | |
const writable = await fileHandle.createWritable(); | |
const response = await fetch(absoluteImageUrl); | |
const blob = await response.blob(); | |
await writable.write(blob); | |
await writable.close(); | |
console.log(`Downloaded: ${fileHandle.name}`); | |
} catch (error) { | |
console.error(`Error downloading image ${index + 1}.jpg:`, error); | |
} | |
}); | |
}) | |
.catch(error => { | |
console.error("Error:", error); | |
}); | |
} | |
async function startDownload() { | |
const url = "https://example.com"; // URL of the web page containing the images | |
const saveDirectoryHandle = await selectDirectory(); | |
if (saveDirectoryHandle) { | |
downloadImages(url, saveDirectoryHandle); | |
} | |
} | |
// Example usage: | |
startDownload(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment