油猴脚本批量下载网页图片

为啥用油猴脚本搞这种东西,主要是用起来比较方便:在网页上加个按钮,小白也会用。
但纯js脚本保存文件是比较麻烦的,使用URLProtocol调用新进程来下载。
如果url很复杂的话又会出现新的问题,见招拆招吧。

以微信公众号文章为例:

powershell下载脚本主体

在下载前调出对话框选择要下载的位置

using namespace System.IO

$script:args = $args
$script:scriptFolder = $PSScriptRoot
$script:urlProtocol = "x-lunoctis-download-files"
$script:targetFolder = ""

function SelectFolder()
{
    $tempFile = "$script:scriptFolder\~DownloadFiles.txt"
    $lastFolder = ""
    if ([File]::Exists($tempFile))
    {
        $lastFolder = [File]::ReadAllText($tempFile)
        Write-Host $lastFolder
        if ([Directory]::Exists($lastFolder) -eq $false)
        {
            $lastFolder = ""
        }
    }

    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.Application]::EnableVisualStyles()

    $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
    if ([string]::IsNullOrEmpty($lastFolder) -eq $false)
    {
        $FolderBrowser.SelectedPath = $lastFolder
    }
    $result = $FolderBrowser.ShowDialog()
    if ($result -ne [System.Windows.Forms.DialogResult]::OK)
    {
        Exit
    }

    $script:targetFolder = $FolderBrowser.SelectedPath

    if ([string]::IsNullOrEmpty($script:targetFolder))
    {
        Exit
    }
    else
    {
        [File]::WriteAllText($tempFile, $script:targetFolder)
    }
}

function Main()
{
    SelectFolder

    $str = $script:args[0]
    $str = $str.Replace($script:urlProtocol + ":", "")

    $index = $str.IndexOf("/")
    $fmt = ""
    if ($index -gt 0)
    {
        $fmt = $str.SubString(0, $index)
        $fmt = "." + $fmt
    }
    $str = $str.SubString($index + 1);

    $urlList = $str -Split "\?\?AND\?\?"
    $count = 0
    foreach ($url in $urlList)
    {
        $count = $count + 1
        $targetFile = "$script:targetFolder\$count$fmt"
        Invoke-WebRequest -Uri $url -OutFile $targetFile
    }
}
Main

安装下载脚本的脚本

需要管理员模式运行

using namespace System
using namespace System.IO

$script:fileName = "DownloadFiles"
$script:urlProtocol = "x-lunoctis-download-files"

###############################
# implement
###############################

$script:userFolder = [Environment]::GetFolderPath(40) # Environment.SpecialFolder.UserProfile
$script:cmdsFolder = "$script:userFolder\.cmds"
$script:scriptFolder = $PSScriptRoot

function CreateRegistryItemProperty([string]$path, [string]$key, [string]$value)
{
    if ((Test-Path -LiteralPath $path) -eq $false)
    {
        New-Item $path | Out-Null
    }

    if ($null -eq (Get-ItemProperty -LiteralPath $path -Name $key -ErrorAction SilentlyContinue))
    {
        New-ItemProperty -LiteralPath $path -Name $key -PropertyType String -Value $value | Out-Null
    }
    else
    {
        Set-ItemProperty -LiteralPath $path -Name $key -Value $value
    }
}

function CreateRegistryItem([string]$path, [string]$value)
{
    CreateRegistryItemProperty $path "(default)" $value
}

function CreateURLProtocol([string]$name, [string]$cmd)
{
    $path = "Registry::HKEY_CLASSES_ROOT\$script:urlProtocol"
    CreateRegistryItem $path "URL:$script:urlProtocol" # description only
    CreateRegistryItemProperty $path "URL Protocol" ""
    CreateRegistryItem "$path\shell" ""
    CreateRegistryItem "$path\shell\open" ""

    $cmd = "powershell ""$script:cmdsFolder\DownloadFiles.ps1"" ""%1"""
    CreateRegistryItem "$path\shell\open\command" $cmd
}

function Main()
{
    if ([Directory]::Exists($script:cmdsFolder) -eq $false)
    {
        [Directory]::CreateDirectory($script:cmdsFolder)
    }

    $srcFile = "$script:scriptFolder\DownloadFiles.ps1"
    $targetFile = "$script:cmdsFolder\DownloadFiles.ps1"
    [File]::Copy($srcFile, $targetFile, $true)

    CreateURLProtocol

    Write-Host "OK"
}
Main

油猴脚本

把要下载的url拼接起来调用URLProtocol

// ==UserScript==
// @name         微信公众号图片下载
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       lunoctis
// @match        https://mp.weixin.qq.com/*
// @require      https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js
// @icon         https://www.google.com/s2/favicons?sz=64&domain=artron.net
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    let main_btn = document.createElement('div');
    main_btn.innerHTML = "下载";
    main_btn.style.cssText = "font-family:siyuan;max-width:60%;min-width: 60px;padding:0 14px;height: 60px;color: rgb(255, 255, 255);line-height: 60px;text-align: center;border-radius: 4px;position: fixed;top: 0%;left: 0%;transform: translate(0%, 0%);z-index: 999999;background: rgba(10, 231, 15,.7);font-size: 30px;";
    document.body.appendChild(main_btn);

    main_btn.onclick = function()
    {
        let rootQuery = $("#js_content");
        if (rootQuery.length == 1)
        {
            let imgQuery = rootQuery.find("img");
            if (imgQuery.length > 0)
            {
                let str = "x-lunoctis-download-files:";
                let fmt = "";

                for (let i = 0; i < imgQuery.length; i++)
                {
                    let node = imgQuery[i];
                    let src = node.dataset.src;
                    if (i === 0)
                    {
                        fmt = node.dataset.type
                        str = str + fmt + "/";
                    }

                    if (i > 0)
                    {
                        str = str + "??AND??";
                    }
                    str = str + src;
                }

                let h = window.open(str);
                h.close();
            }
        }
    }
})();
posted @   lunoctis  阅读(1278)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示