如何用AppleScript/Shell脚本批量下载指定类名图片并按源URL命名
Solution to Scrape & Download Images from URLs with AppleScript
Hey there! I see you've got a start with your AppleScript, but you're missing the key parts for scraping the target images and handling downloads. Let's fix that up—here's a complete, working script that does exactly what you need, plus handles edge cases like invalid filenames and missing images.
Full Working Script
-- Set up the base download folder (same directory as the script) tell application "Finder" set scriptContainer to container of (path to me) as text set downloadFolder to scriptContainer & "Scraped Images:" -- Create the folder if it doesn't exist if not (exists folder downloadFolder) then make new folder at scriptContainer with properties {name:"Scraped Images"} end if end tell -- Your list of target URLs set AllUrls to {"https://teespri...", "https://example.com/another-page"} -- Loop through each URL in the list repeat with currentUrl in AllUrls try -- Clean up the URL to use as a valid filename (replace forbidden characters) set safeFilename to my cleanFilename(currentUrl) set imagePath to downloadFolder & safeFilename & ".jpg" -- Adjust extension if your images use .png etc. -- Use Safari to load the page and extract the image's src via JavaScript tell application "Safari" activate -- Open the URL in a new tab set newTab to make new tab at end of tabs of window 1 set URL of newTab to currentUrl -- Wait for the page to fully load (adjust delay if needed for slow pages) repeat while (do JavaScript "document.readyState" in newTab) is not "complete" delay 1 end repeat -- Execute JS to grab the target image's src attribute set imageSrc to do JavaScript "document.querySelector('.image_stack__image.js-default-img').src" in newTab -- Close the tab to keep things tidy close newTab end tell -- Download the image using curl (more reliable than AppleScript's native methods) set curlCommand to "curl -o " & quoted form of POSIX path of imagePath & " " & quoted form of imageSrc do shell script curlCommand log "Successfully downloaded image from: " & currentUrl on error errMsg log "Failed to process " & currentUrl & ": " & errMsg end try end repeat -- Helper function to convert URLs into valid filenames on cleanFilename(rawUrl) set invalidChars to {":", "/", "\\", "?", "%", "*", "|", "\"", "<", ">"} set cleanedUrl to rawUrl repeat with char in invalidChars set cleanedUrl to my replaceText(cleanedUrl, char, "-") end repeat -- Trim long URLs to avoid filename length limits if length of cleanedUrl > 100 then set cleanedUrl to text 1 thru 100 of cleanedUrl & "..." end if return cleanedUrl end cleanFilename -- Helper function to replace text in strings on replaceText(inputText, findText, replaceText) set AppleScript's text item delimiters to findText set textItems to text items of inputText set AppleScript's text item delimiters to replaceText set outputText to textItems as string set AppleScript's text item delimiters to "" return outputText end replaceText
Key Details Explained
- Folder Auto-Creation: The script makes a "Scraped Images" folder in the same directory as your script if it doesn't already exist, so you don't have to set paths manually.
- Filename Safety: URLs contain characters that aren't allowed in filenames (like
/or:), so thecleanFilenamefunction replaces those with-and trims long URLs to avoid system errors. - Reliable DOM Parsing: Using Safari's JavaScript execution is way more accurate than regex for scraping HTML—
document.querySelectordirectly targets the exact image class you specified. - Curl for Downloads:
curlhandles redirects, different image types, and network quirks better than AppleScript's built-in download commands. - Error Handling: The
try/on errorblock catches issues like failed page loads, missing images, or download errors, and logs them so you can debug easily.
Alternative: Headless Scraping (No Safari Window)
If you don't want Safari to pop up during scraping, you can use JavaScript for Automation (JXA) instead, or pair curl with a lightweight HTML parser like pup (you'd need to install pup via Homebrew first). But the script above is self-contained and works without extra tools.
内容的提问来源于stack exchange,提问作者GTO
相关产品推荐
相关产品推荐

