Tampermonkey油猴 跨域请求下载图片示例

2024-06-22 19:28

本文主要是介绍Tampermonkey油猴 跨域请求下载图片示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Tampermonkey油猴 跨域请求下载图片示例

  • 前言
  • 项目
    • 目标网站
    • 代码编写
  • 运行效果

前言

需要用油猴采集并下载一个网站的图片,直接下下不了,搜了一下,是禁止跨域,使用CORS Unblock也不行,所以使用油猴自带的GM_xmlhttpRequest发送跨域请求。

项目

目标网站

目标网站

代码编写

代码仅作为学习使用,禁止商用。

// ==UserScript==
// @name         ***** Image Downloader and Zipper with GM_xmlhttpRequest
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  Download all matching product images as a zip file from the **** product page using GM_xmlhttpRequest (For learning purposes only)
// @author       slowfeather@163.com
// @match        
// @icon         
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// @require      https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js
// ==/UserScript==(function() {'use strict';// List to store image URLslet imageUrls = new Set();// Function to periodically collect image URLsfunction collectImageUrls() {const imageElements = document.querySelectorAll('img');const regex1 = /*****\.com\/package-screenshot\/.+?_scaled\.jpg$/;const regex2 = /*****\.****\.com\/key-image\/.+?\.jpg$/;imageElements.forEach((img) => {const url = img.src;if ((regex1.test(url) || regex2.test(url)) && !imageUrls.has(url)) {imageUrls.add(url);showNotification('捕获了一张图片地址 :'+url);}});}// Function to show notificationfunction showNotification(message) {const notification = document.createElement('div');notification.innerText = message;notification.style.position = 'fixed';notification.style.top = '50px';notification.style.right = '10px';notification.style.zIndex = 1000;notification.style.backgroundColor = 'lightgreen';notification.style.padding = '5px';notification.style.border = '1px solid green';notification.style.borderRadius = '5px';document.body.appendChild(notification);setTimeout(() => {document.body.removeChild(notification);}, 1000);}// Set an interval to collect image URLs every secondsetInterval(collectImageUrls, 300);// Function to download all images in the list and zip themasync function downloadAndZipImages() {const zip = new JSZip();let count = 0;const fetchImage = (url, filename) => {return new Promise((resolve, reject) => {GM_xmlhttpRequest({method: 'GET',url: url,responseType: 'blob',onload: function(response) {if (response.status === 200) {zip.file(filename, response.response);count++;resolve();} else {reject(`HTTP error! status: ${response.status}`);}},onerror: function(error) {reject(`Failed to fetch image ${url}: ${error}`);}});});};const fetchPromises = Array.from(imageUrls).map((url, index) => {const filename = `image_${index + 1}.jpg`;return fetchImage(url, filename);});try {await Promise.all(fetchPromises);if (count > 0) {const content = await zip.generateAsync({ type: "blob" });saveAs(content, "images.zip");} else {alert("No matching images found.");}} catch (error) {console.error(error);}}// Wait for the page to fully loadwindow.addEventListener('load', () => {// Create a button to trigger the downloadconst button = document.createElement('button');button.innerText = 'Download All Images as Zip';button.style.position = 'fixed';button.style.top = '10px';button.style.right = '10px';button.style.zIndex = 1000;button.addEventListener('click', downloadAndZipImages);document.body.appendChild(button);});
})();

运行效果

成功捕获图片
下载图片

这篇关于Tampermonkey油猴 跨域请求下载图片示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085194

相关文章

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

python运用requests模拟浏览器发送请求过程

《python运用requests模拟浏览器发送请求过程》模拟浏览器请求可选用requests处理静态内容,selenium应对动态页面,playwright支持高级自动化,设置代理和超时参数,根据需... 目录使用requests库模拟浏览器请求使用selenium自动化浏览器操作使用playwright

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

MySQL CTE (Common Table Expressions)示例全解析

《MySQLCTE(CommonTableExpressions)示例全解析》MySQL8.0引入CTE,支持递归查询,可创建临时命名结果集,提升复杂查询的可读性与维护性,适用于层次结构数据处... 目录基本语法CTE 主要特点非递归 CTE简单 CTE 示例多 CTE 示例递归 CTE基本递归 CTE 结

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

Spring Bean初始化及@PostConstruc执行顺序示例详解

《SpringBean初始化及@PostConstruc执行顺序示例详解》本文给大家介绍SpringBean初始化及@PostConstruc执行顺序,本文通过实例代码给大家介绍的非常详细,对大家的... 目录1. Bean初始化执行顺序2. 成员变量初始化顺序2.1 普通Java类(非Spring环境)(