document.querySelectorAll('a.itemimg').forEach(function(item) {
let downloadButton = document.createElement('button');
downloadButton.innerText = 'Save URLs';
downloadButton.style.cssText = `
font-size: 10px;
position: absolute;
bottom: 45px; /* Move the button higher on the page */
right: 0px; /* Adjust as needed for your layout */
background-color: rgba(0, 0, 0, 0.6); /* Background with opacity */
border: 1px solid #f92672;
border-radius: 5px;
padding: 3px;
color: white;
z-index: 1000;
cursor: pointer;
`;
downloadButton.onclick = function(event) {
event.preventDefault(); // Prevent default link behavior
saveImageUrls(item);
};
item.style.position = 'relative'; // Ensure the parent has a position for absolute positioning of the button
item.appendChild(downloadButton);
});
function saveImageUrls(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy'); // Select both nolazy and lazy images
if (!imgElement) return; // No image found, exit function
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title').trim();
let totalImg = parseInt(item.querySelector('.itemset-num .num').innerText, 10);
let imageUrls = [];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
function createTextFileWithUrls(urls, title) {
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${title}.txt`);
GM_notification(`Image URLs saved successfully as ${title}.txt`, 'Save Complete');
}
Assistant
})();
I would like to place the same button, with the same function, on div.picbox . However, the totalImg value has to be collected from the href of div.titlebox . You need to add https://www.xsnvshen.com to the front of href in order to complete the address link. Let's call it TitleLink . From TitleLink, you need to go to em#time.swpt-time span to collect the totalImg value. The numberic value 共 and 张 is the totalImg. As for the imageUrls, the base url is created from the src of picbox by removing thumb_256x384/ and cover.jpg .
Sure! Below is the updated Userscript that adds a "Save URLs" button to both a.itemimg and div.picbox elements on XSNVShen. The script handles both elements as follows:
For a.itemimg Elements:
Functionality: Collects image URLs directly from the a.itemimg element.
Usage: This is the existing functionality you already have.
For div.picbox Elements:
Functionality:
Retrieves the href from the related div.titlebox.
Constructs the full URL (TitleLink) by prefixing it with https://www.xsnvshen.com.
Fetches the TitleLink page to extract the total number of images (totalImg) from the em#time.swpt-time span element.
Constructs the baseUrl from the src of the image in div.picbox by removing thumb_256x384/ and cover.jpg.
Generates the list of image URLs based on the baseUrl and totalImg.
Saves the URLs into a text file named after the title.
Updated Userscript
javascript
// ==UserScript==
// @name XSNVShen Image URL Collector
// @namespace violentmonkey
// @version 1.9
// @description Collects image URLs and saves them into a text file from XSNVShen
// @author Your Name
// @match https://www.xsnvshen.com/*
// @grant GM_notification
// @require https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js
// ==/UserScript==
(function() {
'use strict';
/**
* Creates and appends a "Save URLs" button to a given element.
*
* @param {HTMLElement} element - The element to which the button will be appended.
* @param {string} type - The type of element ('itemimg' or 'picbox') to determine the save function.
*/
function addDownloadButton(element, type) {
let downloadButton = document.createElement('button');
downloadButton.innerText = 'Save URLs';
downloadButton.style.cssText = `
font-size: 10px;
position: absolute;
bottom: 45px; /* Adjust as needed */
right: 0px; /* Adjust as needed */
background-color: rgba(0, 0, 0, 0.6);
border: 1px solid #f92672;
border-radius: 5px;
padding: 3px;
color: white;
z-index: 1000;
cursor: pointer;
`;
downloadButton.onclick = function(event) {
event.preventDefault(); // Prevent default behavior
if (type === 'itemimg') {
saveImageUrlsFromItemImg(element);
} else if (type === 'picbox') {
saveImageUrlsFromPicbox(element);
}
};
// Ensure the parent has a position for absolute positioning of the button
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
element.appendChild(downloadButton);
}
/**
* Adds "Save URLs" buttons to all `a.itemimg` elements.
*/
document.querySelectorAll('a.itemimg').forEach(function(item) {
addDownloadButton(item, 'itemimg');
});
/**
* Adds "Save URLs" buttons to all `div.picbox` elements.
*/
document.querySelectorAll('div.picbox').forEach(function(picbox) {
addDownloadButton(picbox, 'picbox');
});
/**
* Saves image URLs from an `a.itemimg` element.
*
* @param {HTMLElement} item - The `a.itemimg` element.
*/
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy'); // Select both nolazy and lazy images
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return; // No image found, exit function
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
// Construct baseUrl by removing "thumb_205x308/" and "cover.jpg"
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let imageUrls = [];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
/**
* Saves image URLs from a `div.picbox` element.
*
* @param {HTMLElement} picbox - The `div.picbox` element.
*/
async function saveImageUrlsFromPicbox(picbox) {
try {
// Get the img src
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
// Create baseUrl by removing 'thumb_256x384/' and 'cover.jpg'
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
// Find the related 'div.titlebox'
// Adjust the selector based on the actual DOM structure
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
// Construct the full TitleLink
let titleLink = `https://www.xsnvshen.com${href}`;
// Fetch the TitleLink page
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
// Parse the fetched HTML
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
// Select 'em#time.swpt-time span'
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
// Extract the numeric value between '共' and '张' (e.g., "共30张")
let match = timeText.match(/共(\d+)张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
// Get the title from titlebox
let title = linkElement.innerText.trim() || 'untitled';
// Construct image URLs
let imageUrls = [];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
/**
* Creates a text file from the list of URLs and triggers a download.
*
* @param {string[]} urls - Array of image URLs.
* @param {string} title - The title to name the text file.
*/
function createTextFileWithUrls(urls, title) {
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${title}.txt`);
GM_notification(`Image URLs saved successfully as ${title}.txt`, 'Save Complete');
}
})();
Explanation of the Changes
Download Button Functionality for div.picbox:
Button Creation: The addDownloadButton function now accepts a type parameter to differentiate between itemimg and picbox elements. Depending on the type, it assigns the appropriate save function.
Event Handling: When the button is clicked, it calls either saveImageUrlsFromItemImg or saveImageUrlsFromPicbox based on the element type.
Processing div.picbox:
Base URL Construction: Extracts the src from the image within div.picbox, removes thumb_256x384/ and cover.jpg to form the baseUrl.
Fetching totalImg:
Locate div.titlebox: Assumes that div.picbox and div.titlebox are within the same parent container (e.g., div.item). Adjust the selector .item based on the actual page structure.
Construct TitleLink: Prefixes the href from div.titlebox with https://www.xsnvshen.com to form the complete URL.
Fetch and Parse: Retrieves the HTML content of TitleLink and parses it to locate em#time.swpt-time span.
Extract totalImg: Uses a regular expression to extract the numeric value between 共 and 张 (e.g., "共30张" → 30).
URL Generation: Uses the baseUrl and totalImg to generate the list of image URLs.
Error Handling:
Comprehensive error checks are added to notify the user if any step fails, such as missing elements or failed network requests.
Selectors:
Adjusting Selectors: The script uses closest('.item') to find the parent container that likely holds both div.picbox and div.titlebox. You might need to adjust the .item class based on the actual DOM structure of XSNVShen.
Important Notes
Permissions: Ensure that the script has the necessary permissions to fetch pages within https://www.xsnvshen.com/*. Since both the main page and TitleLink are within the same domain, fetch should work without additional permissions. If you encounter cross-origin issues, consider adding the necessary @grant directives or using GM_xmlhttpRequest.
DOM Structure: The success of this script heavily relies on the actual DOM structure of the XSNVShen website. If the elements like div.titlebox or em#time.swpt-time span are nested differently, you'll need to adjust the selectors accordingly.
Styling the Button: The button's styling is minimal. Feel free to adjust the CSS in the style.cssText block to better fit the website's design.
Versioning: The script version has been incremented to 1.9 to reflect the new additions. Update this as you make further changes.
Conclusion
This updated Userscript should fulfill your requirements by adding the "Save URLs" button to both a.itemimg and div.picbox elements, handling the different methods of extracting totalImg, and generating the appropriate list of image URLs. Make sure to test the script and adjust selectors as necessary based on the actual HTML structure of XSNVShen.
Not yet included in a published release.
Flexibility: If div.titlebox isn't found within .item, it attempts to find it within the immediate parent. Modify these selectors as needed to fit the website's structure.