Review and analyse this whole Scraperlib library's codes, after this make the Scraperlib the best of the best possible practically feasible client-side only library you can craft or can think of to make this Scraperlib library more powerful, fast, reliable, bug free, use full, effective, efficient, bottleneck free, error free, memory leaks free, resources efficient, practical better than before.
Think really hard and deeply before coming to the conclusion.
Don't use any external libraries. Always consider and handle all of the possible or potential consequences of your modification so that it's won't introduce any new errors or issues or bugs.
Send the fully practical, usable and working full-complete codes.
/*!
ScraperLib.js v6.7.0
A fully stable, practical, and robust client-side web scraping library ready for production use
License: MIT
*/
(function (global) {
'use strict';
/**
Utility functions for validation and processing
*/
const Utils = {
// Validates if a string is a valid URL
isValidURL(url) {
if (typeof url !== 'string' || url.length > 2048) return false;
try {
new URL(url);
return true;
} catch {
return false;
}
},
code
// Sanitizes a string to prevent XSS
code
Assistant
sanitize(str) {
if (typeof str !== 'string') return '';
const temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
},
// Initializes the cache if available
async initCache() {
if ('caches' in global) {
try {
return await caches.open('scraper-lib-cache');
} catch (e) {
console.error('Cache initialization failed:', e);
return null;
}
}
return null;
},
// Generates a cache key based on URL and options
async generateCacheKey(url, options = {}) {
const cacheOptions = {
useProxy: options.useProxy,
proxyUrl: options.useProxy ? options.proxyUrl : undefined,
selectorsHash: await Utils.hashSelectors(options.selectors),
userAgent: options.userAgent,
acceptLanguage: options.acceptLanguage,
cacheTime: options.cacheTime,
};
// Exclude functions from JSON.stringify
const cacheKeyString = `${url}-${JSON.stringify(cacheOptions, (key, value) => {
if (typeof value === 'function') {
return undefined;
}
return value;
})}`;
const hash = await Utils.hashString(cacheKeyString);
return hash;
},
// Generates a hash for selectors to include in cache key
async hashSelectors(selectors) {
if (!selectors) return '';
try {
const selectorsString = JSON.stringify(selectors, (key, value) => {
if (typeof value === 'function') {
return undefined; // Exclude functions from JSON.stringify
}
return value;
});
return await Utils.hashString(selectorsString);
} catch (e) {
console.error('Error hashing selectors:', e);
return '';
}
},
// Generates a cryptographic hash from a string
async hashString(str) {
if (typeof crypto !== 'undefined' && crypto.subtle) {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
} else {
// Fallback to a simple hash function
let hash = 0,
i,
chr;
if (str.length === 0) return hash.toString();
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash.toString();
}
},
// Validates and normalizes CSS selectors
normalizeSelector(selector) {
if (typeof selector !== 'string') throw new Error('Selector must be a string');
try {
document.createDocumentFragment().querySelector(selector);
return selector;
} catch {
throw new Error(`Invalid CSS selector: "${selector}"`);
}
},
// Deep merge of objects
deepMerge(target, ...sources) {
target = target || {};
sources.forEach(src => {
if (src && typeof src === 'object') {
Object.keys(src).forEach(key => {
const value = src[key];
if (
value &&
typeof value === 'object' &&
!Array.isArray(value) &&
!(value instanceof RegExp)
) {
target[key] = Utils.deepMerge(target[key], value);
} else {
target[key] = value;
}
});
}
});
return target;
},
// Extracts text from an element, optionally preserving formatting
extractText(element, options = {}) {
if (!element) return '';
const clone = element.cloneNode(true);
// Remove scripts and styles
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
if (options.preserveFormatting) {
// Replace <br> with newline characters
clone.querySelectorAll('br').forEach(br => {
const textNode = document.createTextNode('\n');
br.parentNode.replaceChild(textNode, br);
});
// Add newline after </p> elements
clone.querySelectorAll('p').forEach(p => {
const textNode = document.createTextNode('\n');
p.appendChild(textNode);
});
}
return clone.textContent.trim();
},
// Removes scripts and styles from HTML string
removeScriptsAndStyles(html) {
try {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('script, style, noscript').forEach(el => el.remove());
return doc.documentElement.outerHTML;
} catch (e) {
console.error('Error parsing HTML for script/style removal:', e);
return html
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
.replace(/<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi, '');
}
},
// Chunks an array into smaller arrays of specified size
chunkArray(array, size) {
if (!Array.isArray(array)) throw new Error('Input must be an array');
if (!Number.isInteger(size) || size <= 0) throw new Error('Chunk size must be a positive integer');
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
},
// Parses a string to JSON safely
safeParseJSON(str) {
try {
return JSON.parse(str);
} catch {
return null;
}
},
// Converts a NodeList to an Array
nodeListToArray(nodeList) {
return Array.from(nodeList);
},
// Function to delay execution
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
},
// Check for anti-scraping mechanisms (e.g., CAPTCHA)
detectAntiScraping(html) {
// Simple keyword detection for common anti-scraping messages
const antiScrapingKeywords = [
'captcha',
'verify you are human',
'access denied',
'bot detection',
'unusual traffic',
'request blocked',
'please enable cookies',
];
const lowerHtml = html.toLowerCase();
return antiScrapingKeywords.some(keyword => lowerHtml.includes(keyword));
},
// Built-in filters for common operations
builtInFilters: {
trim: value => (typeof value === 'string' ? value.trim() : value),
toUpperCase: value => (typeof value === 'string' ? value.toUpperCase() : value),
toLowerCase: value => (typeof value === 'string' ? value.toLowerCase() : value),
parseInt: value => parseInt(value, 10),
parseFloat: value => parseFloat(value),
// Additional built-in filters
replace: (value, args) => {
if (typeof value !== 'string' || !Array.isArray(args) || args.length < 2) return value;
const [pattern, replacement] = args;
let regex;
if (pattern instanceof RegExp) {
regex = pattern;
} else if (typeof pattern === 'string') {
regex = new RegExp(pattern, 'g');
} else {
return value;
}
return value.replace(regex, replacement);
},
substring: (value, args) => {
if (typeof value !== 'string' || !Array.isArray(args)) return value;
return value.substring(args[0], args[1]);
},
split: (value, args) => {
if (typeof value !== 'string' || !Array.isArray(args)) return value;
return value.split(args[0]);
},
join: (value, args) => {
if (!Array.isArray(value)) return value;
return value.join(args[0]);
},
regexMatch: (value, args) => {
if (typeof value !== 'string' || !Array.isArray(args) || args.length < 1) return value;
const [pattern, group = 0] = args;
let regex;
if (pattern instanceof RegExp) {
regex = pattern;
} else if (typeof pattern === 'string') {
regex = new RegExp(pattern);
} else {
return value;
}
const match = value.match(regex);
return match ? match[group] : null;
},
// Additional filters can be added here
},
};
/**
Handles storing scraped data
*/
class StorageHandler {
constructor() {
this.dbPromise = null;
this.storeName = 'scrapedData';
if ('indexedDB' in global) {
this.storageType = 'indexeddb';
this.dbPromise = this.initIndexedDB();
} else if ('localStorage' in global && this._isLocalStorageAccessible()) {
this.storageType = 'localstorage';
} else {
this.storageType = 'memory';
this.memoryStorage = new Map();
}
}
code
_isLocalStorageAccessible() {
code
try {
const testKey = '__test__';
localStorage.setItem(testKey, testKey);
localStorage.removeItem(testKey);
return true;
} catch {
console.warn('localStorage is not accessible. Using in-memory storage.');
return false;
}
}
async initIndexedDB(dbName = 'ScraperLibDB') {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onerror = () => reject(new Error('IndexedDB initialization failed'));
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.storeName)) {
const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true });
store.createIndex('url', 'url', { unique: false });
store.createIndex('timestamp', 'timestamp', { unique: false });
}
};
request.onsuccess = event => {
const db = event.target.result;
db.onerror = event => {
console.error('Database error:', event.target.error);
};
resolve(db);
};
});
}
async store(url, data, format, options = {}) {
const timestamp = Date.now();
const storeData = { url, data, timestamp };
switch (format) {
case 'indexeddb':
if (this.dbPromise) {
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
const transaction = db.transaction(this.storeName, 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.add(storeData);
request.onsuccess = () => resolve(true);
request.onerror = () => reject(request.error);
});
}
throw new Error('IndexedDB is not supported or initialized');
case 'localstorage':
try {
const key = `scraper-${url}-${timestamp}`;
localStorage.setItem(key, JSON.stringify(storeData));
return true;
} catch (e) {
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
this._cleanupLocalStorage();
const key = `scraper-${url}-${timestamp}`;
localStorage.setItem(key, JSON.stringify(storeData));
return true;
}
throw e;
}
case 'memory':
this.memoryStorage.set(`${url}-${timestamp}`, storeData);
return true;
case 'custom':
if (options.customStore && typeof options.customStore.save === 'function') {
await options.customStore.save(url, data);
return true;
}
throw new Error('Invalid custom storage handler');
default:
throw new Error(`Unsupported storage format: ${format}`);
}
}
_cleanupLocalStorage() {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith('scraper-')) {
keys.push(key);
}
}
if (keys.length > 100) {
keys.sort((a, b) => {
try {
const itemA = Utils.safeParseJSON(localStorage.getItem(a));
const itemB = Utils.safeParseJSON(localStorage.getItem(b));
return itemA.timestamp - itemB.timestamp;
} catch (e) {
localStorage.removeItem(a);
localStorage.removeItem(b);
return 0;
}
});
for (let i = 0; i < keys.length - 100; i++) {
localStorage.removeItem(keys[i]);
}
}
}
async retrieve(url, format) {
switch (format) {
case 'indexeddb':
if (this.dbPromise) {
const db = await this.dbPromise;
return new Promise((resolve, reject) => {
const transaction = db.transaction(this.storeName, 'readonly');
const store = transaction.objectStore(this.storeName);
const index = store.index('url');
const request = index.getAll(url);
request.onsuccess = () => {
const results = request.result;
if (results && results.length > 0) {
results.sort((a, b) => b.timestamp - a.timestamp);
resolve(results[0].data);
} else {
resolve(null);
}
};
request.onerror = () => reject(request.error);
});
}
throw new Error('IndexedDB is not supported or initialized');
case 'localstorage':
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(`scraper-${url}-`)) {
keys.push(key);
}
}
keys.sort((a, b) => {
const itemA = Utils.safeParseJSON(localStorage.getItem(a));
const itemB = Utils.safeParseJSON(localStorage.getItem(b));
return (itemB?.timestamp || 0) - (itemA?.timestamp || 0);
});
if (keys.length > 0) {
const item = Utils.safeParseJSON(localStorage.getItem(keys[0]));
return item ? item.data : null;
}
return null;
case 'memory':
const memoryItems = Array.from(this.memoryStorage.entries())
.filter(([key]) => key.startsWith(`${url}-`))
.sort((a, b) => b[1].timestamp - a[1].timestamp);
if (memoryItems.length > 0) {
return memoryItems[0][1].data;
}
return null;
default:
throw new Error(`Unsupported storage format: ${format}`);
}
}
// Merge and validate default settings with user options
this.settings = Utils.deepMerge({}, this.defaultSettings, options);
this._validateSettings(this.settings);
// Initialize per-URL settings
this.urlSettings = new Map();
this.storage = new StorageHandler();
this.rateLimiter = new RateLimiter(this.settings.rateLimitRequests);
this.cache = null;
this.errorHandlers = new Map();