Add 1 files
Browse files2 unmodified lines345678912 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727315 unmodified lines8990919293941 unmodified line969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line13013113213313413513613713813914011 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712727 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043053063073086 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363373383 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823832 unmodified lines3863873883893903913923933943953963973987 unmodified lines40640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910302 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>SmartScrape Pro - Advanced Web Scraping Tool</title><script src="https://cdn.tailwindcss.com"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><style>12 unmodified lines100% { transform: rotate(360deg); }}.fade-in {animation: fadeIn 0.3s ease-in;}@keyframes fadeIn {from { opacity: 0; transform: translateY(10px); }to { opacity: 1; transform: translateY(0); }}.error-shake {animation: shake 0.5s;}@keyframes shake {0%, 100% { transform: translateX(0); }10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }20%, 40%, 60%, 80% { transform: translateX(5px); }}.preview-image {max-width: 100%;max-height: 150px;border: 1px solid #e5e7eb;border-radius: 0.375rem;margin-top: 0.5rem;}.content-preview {background-color: #f9fafb;border-left: 3px solid #3b82f6;padding: 0.75rem;margin-top: 0.5rem;border-radius: 0.25rem;font-size: 0.875rem;max-height: 150px;overflow-y: auto;}.preview-toggle {color: #3b82f6;cursor: pointer;font-size: 0.75rem;margin-top: 0.25rem;display: inline-block;}.progress-bar {width: 100%;height: 8px;15 unmodified linesmargin-top: 0.5rem;font-style: italic;}</style></head><body class="bg-gray-50 min-h-screen">1 unmodified line<!-- Header --><header class="text-center mb-8"><h1 class="text-4xl font-bold text-blue-600 mb-2"><i class="fas fa-robot mr-2"></i>SmartScrape Pro</h1><p class="text-gray-600">Advanced web scraping tool with preview and flexible download options</p></header><!-- Main Form --><div class="bg-white rounded-xl shadow-md p-6 mb-8"><div class="flex flex-col md:flex-row gap-4 mb-6"><div class="flex-grow"><label for="url" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-link mr-1"></i> Enter URL to scrape</label><div class="flex"><inputtype="url"id="url"placeholder="https://example.com/page"class="flex-grow px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-blue-500 focus:border-blue-500"requiredvalue="https://example.com/news/article"><buttonid="analyzeBtn"class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-r-lg transition duration-200"><i class="fas fa-search mr-1"></i> Analyze</button></div></div></div>1 unmodified line<!-- Loading State --><div id="loading" class="hidden text-center py-8"><div class="loading-spinner mb-4"></div><p class="text-gray-600">Analyzing the webpage structure...</p><div class="progress-bar mt-4"><div id="progressBarFill" class="progress-bar-fill" style="width: 0%"></div></div><p id="statusMessage" class="status-message"></p></div><!-- Error Message -->11 unmodified lines</div></div><!-- Scraping Options (Initially Hidden) --><div id="scrapingOptions" class="hidden fade-in"><h2 class="text-xl font-semibold text-gray-800 mb-4"><i class="fas fa-cogs mr-2"></i>Scraping Options</h2><!-- Detected Content --><div class="mb-6"><h3 class="text-lg font-medium text-gray-700 mb-2"><i class="fas fa-list-ul mr-1"></i>Detected Content (click to preview)</h3><div id="detectedContent" class="grid grid-cols-1 md:grid-cols-2 gap-3"><!-- Content will be populated by JavaScript --></div></div><!-- Output Format --><div class="mb-6"><h3 class="text-lg font-medium text-gray-700 mb-2"><i class="fas fa-file-export mr-1"></i>Output Format</h3><div class="flex flex-wrap gap-3"><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="json" class="h-4 w-4 text-blue-600" checked><span class="ml-2 text-gray-700">JSON</span></label><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="csv" class="h-4 w-4 text-blue-600"><span class="ml-2 text-gray-700">CSV</span></label><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="xml" class="h-4 w-4 text-blue-600"><span class="ml-2 text-gray-700">XML</span></label><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="html" class="h-4 w-4 text-blue-600"><span class="ml-2 text-gray-700">HTML Table</span></label></div></div><!-- Download Options --><div class="mb-6"><h3 class="text-lg font-medium text-gray-700 mb-2"><i class="fas fa-download mr-1"></i>Download Options</h3><div class="bg-gray-50 p-4 rounded-lg"><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1">Image Naming Convention</label><select id="imageNaming" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"><option value="title_index">Article Title + Index (e.g., "Article_1.jpg")</option><option value="title_alt">Article Title + Alt Text (e.g., "Article_image-description.jpg")</option><option value="original">Original Filename</option></select></div><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1">Image Format</label><select id="imageFormat" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"><option value="jpg">JPG</option><option value="png">PNG</option><option value="original">Original Format</option></select></div><div><label class="inline-flex items-center"><input type="checkbox" id="chooseLocation" class="h-4 w-4 text-blue-600"><span class="ml-2 text-sm text-gray-700">Let me choose download location</span></label></div></div></div><!-- Advanced Options --><div class="mb-6"><div class="flex items-center mb-2 cursor-pointer" id="advancedToggle"><h3 class="text-lg font-medium text-gray-700"><i class="fas fa-sliders-h mr-1"></i>Advanced Options</h3><i class="fas fa-chevron-down ml-2 text-gray-500 text-sm" id="advancedIcon"></i></div><div id="advancedOptions" class="hidden bg-gray-50 p-4 rounded-lg"><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1">Pagination</label><select id="pagination" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"><option value="none">Single page only</option><option value="next">Follow "next page" links</option><option value="numbered">Follow numbered pages (1, 2, 3...)</option></select></div><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1">Delay between requests (ms)</label><input type="number" id="requestDelay" min="0" value="1000" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"></div><div><label class="inline-flex items-center"><input type="checkbox" id="includeMetadata" class="h-4 w-4 text-blue-600"><span class="ml-2 text-sm text-gray-700">Include metadata (URL, timestamp)</span></label></div></div></div><!-- Scrape Button --><div class="text-center"><buttonid="scrapeBtn"class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-medium transition duration-200"><i class="fas fa-download mr-2"></i>Scrape Data</button></div></div><!-- Results Section (Initially Hidden) --><div id="resultsSection" class="hidden fade-in mt-8"><div class="flex justify-between items-center mb-4"><h2 class="text-xl font-semibold text-gray-800"><i class="fas fa-file-alt mr-2"></i>Scraped Data7 unmodified lines</button></div></div><div class="bg-gray-50 p-4 rounded-lg"><pre id="resultsOutput" class="overflow-auto max-h-96 text-sm bg-white p-3 rounded border border-gray-200"></pre></div><!-- Image Download Section --><div id="imageDownloadSection" class="hidden mt-6"><h2 class="text-xl font-semibold text-gray-800 mb-4"><i class="fas fa-images mr-2"></i>Download Images</h2><div class="bg-gray-50 p-4 rounded-lg"><p class="text-gray-600 mb-4">The following images will be downloaded with your selected naming convention:</p><div id="imagePreviewGrid" class="grid grid-cols-2 md:grid-cols-3 gap-4"><!-- Image previews will be added here --></div><div class="mt-4 text-center"><buttonid="downloadImagesBtn"class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2 rounded-lg font-medium transition duration-200"><i class="fas fa-image mr-2"></i>Download Images</button></div></div></div></div></div>6 unmodified lines<div class="grid grid-cols-1 md:grid-cols-3 gap-4"><div class="bg-blue-50 p-4 rounded-lg"><div class="text-blue-600 mb-2"><i class="fas fa-search fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">1. Analyze & Preview</h3><p class="text-sm text-gray-600">Enter any webpage URL and preview exactly what content will be scraped.</p></div><div class="bg-purple-50 p-4 rounded-lg"><div class="text-purple-600 mb-2"><i class="fas fa-cog fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">2. Customize</h3><p class="text-sm text-gray-600">Select content, output format, and customize image downloads.</p></div><div class="bg-green-50 p-4 rounded-lg"><div class="text-green-600 mb-2"><i class="fas fa-download fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">3. Download</h3><p class="text-sm text-gray-600">Get your structured data and images exactly how you want them.</p></div></div></div>3 unmodified linesdocument.addEventListener('DOMContentLoaded', function() {// DOM Elementsconst urlInput = document.getElementById('url');const analyzeBtn = document.getElementById('analyzeBtn');const loading = document.getElementById('loading');const errorContainer = document.getElementById('errorContainer');const errorTitle = document.getElementById('errorTitle');const errorMessage = document.getElementById('errorMessage');const scrapingOptions = document.getElementById('scrapingOptions');const detectedContent = document.getElementById('detectedContent');const scrapeBtn = document.getElementById('scrapeBtn');const resultsSection = document.getElementById('resultsSection');const resultsOutput = document.getElementById('resultsOutput');const copyBtn = document.getElementById('copyBtn');const downloadBtn = document.getElementById('downloadBtn');const advancedToggle = document.getElementById('advancedToggle');const advancedOptions = document.getElementById('advancedOptions');const advancedIcon = document.getElementById('advancedIcon');const imageDownloadSection = document.getElementById('imageDownloadSection');const imagePreviewGrid = document.getElementById('imagePreviewGrid');const downloadImagesBtn = document.getElementById('downloadImagesBtn');const chooseLocation = document.getElementById('chooseLocation');const progressBarFill = document.getElementById('progressBarFill');const statusMessage = document.getElementById('statusMessage');// Current scraped datalet currentData = [];let currentImages = [];// Toggle advanced optionsadvancedToggle.addEventListener('click', function() {advancedOptions.classList.toggle('hidden');if (advancedOptions.classList.contains('hidden')) {advancedIcon.classList.remove('fa-chevron-up');advancedIcon.classList.add('fa-chevron-down');} else {advancedIcon.classList.remove('fa-chevron-down');advancedIcon.classList.add('fa-chevron-up');}});// Update progress bar and status2 unmodified linesstatusMessage.textContent = message;}// Analyze button click handleranalyzeBtn.addEventListener('click', function() {const url = urlInput.value.trim();// Validate URLif (!url) {showError('Missing URL', 'Please enter a valid URL to analyze.');urlInput.focus();return;}7 unmodified linesreturn;}// Show loading stateloading.classList.remove('hidden');errorContainer.classList.add('hidden');scrapingOptions.classList.add('hidden');resultsSection.classList.add('hidden');imageDownloadSection.classList.add('hidden');// Reset progressupdateProgress(0, 'Initializing analysis...');// Simulate analysis stepsconst steps = [{percent: 20, message: 'Connecting to website...'},{percent: 40, message: 'Analyzing page structure...'},{percent: 60, message: 'Identifying content elements...'},{percent: 80, message: 'Generating preview options...'},{percent: 100, message: 'Analysis complete!'}];let currentStep = 0;const interval = setInterval(() => {if (currentStep < steps.length) {updateProgress(steps[currentStep].percent, steps[currentStep].message);currentStep++;} else {clearInterval(interval);// Randomly decide if we should show an error (for demo purposes)if (Math.random() < 0.1) {const possibleErrors = [{title: "Access Denied",message: "The website has blocked our scraping bot. Try a different URL or check if the website allows scraping in its robots.txt file."},{title: "Page Not Found",message: "The URL you entered returned a 404 error. Please check the URL and try again."},{title: "Timeout Error",message: "The server took too long to respond. The website might be down or experiencing high traffic."},{title: "Unsupported Content",message: "This page contains dynamic content that requires JavaScript to render. Our bot currently only works with static HTML content."}];const error = possibleErrors[Math.floor(Math.random() * possibleErrors.length)];showError(error.title, error.message);loading.classList.add('hidden');return;}// Show scraping options with detected contentloading.classList.add('hidden');populateDetectedContent();scrapingOptions.classList.remove('hidden');}}, 800);});// Scrape button click handlerscrapeBtn.addEventListener('click', function() {// Show loading stateloading.classList.remove('hidden');errorContainer.classList.add('hidden');// Get selected optionsconst selectedFormat = document.querySelector('input[name="outputFormat"]:checked').value;const selectedItems = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).filter(checkbox => checkbox.name === 'contentItem').map(checkbox => checkbox.value);if (selectedItems.length === 0) {showError('No Selection', 'Please select at least one content type to scrape.');loading.classList.add('hidden');return;}// Reset progressupdateProgress(0, 'Initializing scraping process...');// Simulate scraping stepsconst steps = [{percent: 10, message: 'Connecting to website...'},{percent: 25, message: 'Extracting text content...'},{percent: 40, message: 'Processing images...'},{percent: 60, message: 'Organizing data structure...'},{percent: 80, message: 'Formatting output...'},{percent: 100, message: 'Scraping complete!'}];let currentStep = 0;const interval = setInterval(() => {if (currentStep < steps.length) {updateProgress(steps[currentStep].percent, steps[currentStep].message);currentStep++;} else {clearInterval(interval);loading.classList.add('hidden');// Generate sample data based on selected formatcurrentData = generateSampleData(selectedItems);currentImages = extractImagesFromData(currentData);let result;switch(selectedFormat) {case 'json':result = JSON.stringify(currentData, null, 2);break;case 'csv':result = convertToCSV(currentData);break;case 'xml':result = convertToXML(currentData);break;case 'html':result = convertToHTML(currentData);break;}// Display resultsresultsOutput.textContent = result;resultsSection.classList.remove('hidden');// Show image download section if images were selectedif (selectedItems.includes('images') && currentImages.length > 0) {populateImagePreviews(currentImages);imageDownloadSection.classList.remove('hidden');} else {imageDownloadSection.classList.add('hidden');}}}, 600);});// Copy button click handlercopyBtn.addEventListener('click', function() {navigator.clipboard.writeText(resultsOutput.textContent).then(() => {const originalText = copyBtn.innerHTML;copyBtn.innerHTML = '<i class="fas fa-check mr-1"></i>Copied!';setTimeout(() => {copyBtn.innerHTML = originalText;}, 2000);}).catch(err => {showError('Copy Failed', 'Failed to copy text to clipboard.');});});// Download button click handlerdownloadBtn.addEventListener('click', function() {const selectedFormat = document.querySelector('input[name="outputFormat"]:checked').value;const data = resultsOutput.textContent;const blob = new Blob([data], { type: getMimeType(selectedFormat) });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;// Set filename based on formatlet filename = 'scraped_data';switch(selectedFormat) {case 'json': filename += '.json'; break;case 'csv': filename += '.csv'; break;case 'xml': filename += '.xml'; break;case 'html': filename += '.html'; break;}a.download = filename;// In a real app, you would use a more sophisticated method to let users choose location// This is a simplified version for demonstrationif (chooseLocation.checked) {const userPath = prompt('Enter download path (e.g., C:\\Downloads\\) or leave blank for default:');if (userPath !== null) {filename = (userPath || '') + filename;}}a.download = filename;document.body.appendChild(a);a.click();document.body.removeChild(a);// Revoke the object URL after some time to free up memorysetTimeout(() => {URL.revokeObjectURL(url);}, 100);});// Helper function to get MIME typefunction getMimeType(format) {switch(format) {case 'json': return 'application/json';case 'csv': return 'text/csv';case 'xml': return 'application/xml';case 'html': return 'text/html';default: return 'text/plain';}}// Download Images button click handlerdownloadImagesBtn.addEventListener('click', function() {if (currentImages.length === 0) return;// Show loading stateloading.classList.remove('hidden');updateProgress(0, 'Preparing images for download...');// Simulate download stepsconst steps = currentImages.map((img, index) => ({percent: Math.floor((index + 1) / currentImages.length * 100),message: `Downloading image ${index + 1} of ${currentImages.length}...`}));let currentStep = 0;const interval = setInterval(() => {if (currentStep < steps.length) {updateProgress(steps[currentStep].percent, steps[currentStep].message);currentStep++;} else {clearInterval(interval);loading.classList.add('hidden');// In a real app, you would actually download the images// This is a simulation that shows what would happenconst namingConvention = document.getElementById('imageNaming').value;const imageFormat = document.getElementById('imageFormat').value;let downloadPath = '';if (chooseLocation.checked) {downloadPath = prompt('Enter download path for images (e.g., C:\\Downloads\\images\\) or leave blank for default:') || '';}// Show success messagealert(`Successfully downloaded ${currentImages.length} images to ${downloadPath || 'default location'}`);}}, 500);});// Helper function to show error messagesfunction showError(title, message) {errorTitle.textContent = title;errorMessage.innerHTML = `<p>${message}</p>`;errorContainer.classList.remove('hidden');errorContainer.classList.add('error-shake');setTimeout(() => {errorContainer.classList.remove('error-shake');}, 500);}// Helper function to populate detected content with previewsfunction populateDetectedContent() {detectedContent.innerHTML = '';// Possible content types with sample previewsconst contentTypes = [{id: 'titles',name: 'Article Titles',description: 'Main headings from the page',checked: true,preview: '<div class="content-preview">Sample Article Title</div>'},{id: 'paragraphs',name: 'Paragraphs',description: 'Text content from paragraphs',checked: true,preview: '<div class="content-preview">This is a sample paragraph that would be extracted from the page. It shows the kind of text content you can expect to get when selecting this option.</div>'},{id: 'images',name: 'Images',description: 'All images with their alt text',checked: false,preview: '<img src="https://via.placeholder.com/300x200?text=Sample+Image" alt="Sample image" class="preview-image"><div class="text-xs mt-1">Alt text: "Sample image"</div>'},{id: 'links',name: 'Links',description: 'Hyperlinks with their text and URLs',checked: false,preview: '<div class="content-preview">• <a href="#" class="text-blue-600">Sample Link</a> (https://example.com)</div>'},{id: 'tables',name: 'Tables',description: 'Tabular data from HTML tables',checked: false,preview: '<div class="content-preview">| Header 1 | Header 2 |\n|---------|---------|\n| Data 1 | Data 2 |</div>'},{id: 'lists',name: 'Lists',description: 'Items from ordered and unordered lists',checked: false,preview: '<div class="content-preview">• List item 1\n• List item 2\n• List item 3</div>'},{id: 'metadata',name: 'Metadata',description: 'Page title, description, and keywords',checked: true,preview: '<div class="content-preview">Title: Sample Page\nDescription: This is a sample description\nKeywords: sample, test, scraping</div>'},{id: 'comments',name: 'Comments',description: 'User comments from the page',checked: false,preview: '<div class="content-preview">• User1: "This is a sample comment." (2023-06-01)\n• User2: "Another example comment." (2023-06-02)</div>'}];contentTypes.forEach(item => {const itemDiv = document.createElement('div');itemDiv.className = 'bg-gray-50 p-3 rounded-lg border border-gray-200';// Create a unique ID for the preview toggleconst previewId = `preview-${item.id}`;itemDiv.innerHTML = `<div class="flex items-start"><div class="flex items-center h-5"><inputid="content-${item.id}"name="contentItem"type="checkbox"value="${item.id}"class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"${item.checked ? 'checked' : ''}></div><div class="ml-3 text-sm"><label for="content-${item.id}" class="font-medium text-gray-700 cursor-pointer">${item.name}</label><p class="text-gray-500">${item.description}</p><span class="preview-toggle" onclick="document.getElementById('${previewId}').classList.toggle('hidden')"><i class="fas fa-eye mr-1"></i>Preview</span><div id="${previewId}" class="hidden">${item.preview}</div></div></div>`;detectedContent.appendChild(itemDiv);});}// Helper function to generate sample datafunction generateSampleData(selectedItems) {const data = [];for (let i = 1; i <= 3; i++) {const item = {articleTitle: `Sample Article Title ${i}`};if (selectedItems.includes('titles')) {item.title = item.articleTitle;}if (selectedItems.includes('paragraphs')) {item.paragraph = `This is sample paragraph ${i} with some example content that might be scraped from a webpage. The content varies based on what's available on the page.`;}if (selectedItems.includes('images')) {item.images = [{src: `https://via.placeholder.com/600x400?text=Article+${i}+Image+1`,alt: `Primary image for article ${i}`},{src: `https://via.placeholder.com/300x200?text=Article+${i}+Image+2`,alt: `Secondary image for article ${i}`}];}if (selectedItems.includes('links')) {item.links = [{ text: `Link ${i} to example.com`, url: 'https://example.com' },{ text: `Link ${i} to google.com`, url: 'https://google.com' }];}if (selectedItems.includes('tables')) {item.table = {headers: ['Header 1', 'Header 2', 'Header 3'],rows: [[`Row ${i} Col 1`, `Row ${i} Col 2`, `Row ${i} Col 3`],[`Row ${i+1} Col 1`, `Row ${i+1} Col 2`, `Row ${i+1} Col 3`]]};}if (selectedItems.includes('lists')) {item.list = [`List item ${i}.1`,`List item ${i}.2`,`List item ${i}.3`];}if (selectedItems.includes('metadata')) {item.metadata = {title: `Sample Page ${i}`,description: `This is a sample description for page ${i}`,keywords: `sample, test, scraping, demo`};}if (selectedItems.includes('comments')) {item.comments = [{ author: `User${i}`, text: `This is a sample comment ${i}.1`, date: '2023-06-01' },{ author: `User${i+1}`, text: `This is a sample comment ${i}.2`, date: '2023-06-02' }];}data.push(item);}return data;}// Helper function to extract images from datafunction extractImagesFromData(data) {const images = [];data.forEach(item => {if (item.images && item.images.length > 0) {item.images.forEach(img => {images.push({src: img.src,alt: img.alt,articleTitle: item.articleTitle});});}});return images;}// Helper function to populate image previewsfunction populateImagePreviews(images) {imagePreviewGrid.innerHTML = '';const namingConvention = document.getElementById('imageNaming').value;const imageFormat = document.getElementById('imageFormat').value;images.forEach((img, index) => {let filename = '';// Determine filename based on naming conventionswitch(namingConvention) {case 'title_index':filename = `${img.articleTitle.replace(/[^a-z0-9]/gi, '_')}_${index + 1}.${imageFormat}`;break;case 'title_alt':const altText = img.alt ? img.alt.replace(/[^a-z0-9]/gi, '_').substring(0, 20) : 'image';filename = `${img.articleTitle.replace(/[^a-z0-9]/gi, '_')}_${altText}.${imageFormat}`;break;case 'original':const originalName = img.src.split('/').pop();filename = originalName.includes('.') ? originalName : `${originalName}.${imageFormat}`;break;}const imgDiv = document.createElement('div');imgDiv.className = 'bg-white p-2 rounded border border-gray-200';imgDiv.innerHTML = `<img src="${img.src}" alt="${img.alt || 'image'}" class="w-full h-32 object-cover rounded"><div class="mt-2 text-xs text-gray-600 truncate" title="${filename}">${filename}</div><div class="text-xs text-gray-500 mt-1">From: ${img.articleTitle}</div>`;imagePreviewGrid.appendChild(imgDiv);});}// Helper function to convert to CSVfunction convertToCSV(data) {if (data.length === 0) return '';// Extract headersconst headers = new Set();data.forEach(item => {Object.keys(item).forEach(key => headers.add(key));});const headerArray = Array.from(headers);let csv = headerArray.join(',') + '\n';// Add rowsdata.forEach(item => {const row = headerArray.map(header => {if (item[header] === undefined) return '';if (typeof item[header] === 'object') {return `"${JSON.stringify(item[header]).replace(/"/g, '""')}"`;}return `"${String(item[header]).replace(/"/g, '""')}"`;});csv += row.join(',') + '\n';});return csv;}// Helper function to convert to XMLfunction convertToXML(data) {let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<items>\n';data.forEach((item, index) => {xml += ` <item id="${index + 1}">\n`;Object.entries(item).forEach(([key, value]) => {if (typeof value === 'object') {xml += ` <${key}>\n`;if (Array.isArray(value)) {value.forEach((subItem, subIndex) => {if (typeof subItem === 'object') {xml += ` <item id="${subIndex + 1}">\n`;Object.entries(subItem).forEach(([subKey, subValue]) => {xml += ` <${subKey}>${escapeXML(subValue)}</${subKey}>\n`;});xml += ` </item>\n`;} else {xml += ` <item>${escapeXML(subItem)}</item>\n`;}});} else {Object.entries(value).forEach(([subKey, subValue]) => {xml += ` <${subKey}>${escapeXML(subValue)}</${subKey}>\n`;});}xml += ` </${key}>\n`;} else {xml += ` <${key}>${escapeXML(value)}</${key}>\n`;}});xml += ` </item>\n`;});xml += '</items>';return xml;}// Helper function to escape XML special charactersfunction escapeXML(str) {return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');}// Helper function to convert to HTML tablefunction convertToHTML(data) {if (data.length === 0) return '';// Extract headersconst headers = new Set();data.forEach(item => {Object.keys(item).forEach(key => headers.add(key));});const headerArray = Array.from(headers);let html = '<table border="1" cellpadding="5" cellspacing="0">\n';// Add header rowhtml += ' <tr>\n';headerArray.forEach(header => {html += ` <th>${header}</th>\n`;});html += ' </tr>\n';// Add data rowsdata.forEach(item => {html += ' <tr>\n';headerArray.forEach(header => {let content = '';if (item[header] === undefined) {content = '';} else if (typeof item[header] === 'object') {if (Array.isArray(item[header])) {content = '<ul>' + item[header].map(subItem =>`<li>${typeof subItem === 'object'? JSON.stringify(subItem): String(subItem)}</li>`).join('') + '</ul>';} else {content = '<dl>' + Object.entries(item[header]).map(([key, value]) =>`<dt>${key}</dt><dd>${value}</dd>`).join('') + '</dl>';}} else {content = String(item[header]);}html += ` <td>${content}</td>\n`;});html += ' </tr>\n';});html += '</table>';return html;}});</script><p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Kareem722/web" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>2 unmodified lines345678912 unmodified lines22232425262715 unmodified lines43444546474849505152535455565758596061626364656667681 unmodified line7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line14114214314414514614714814915015111 unmodified lines1631641651661671681691707 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102116 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402413 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982 unmodified lines3013023033043053063073083093103113123133143153163173183193203213223233247 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306312 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Real Web Scraper</title><script src="https://cdn.tailwindcss.com"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><style>12 unmodified lines100% { transform: rotate(360deg); }}.progress-bar {width: 100%;height: 8px;15 unmodified linesmargin-top: 0.5rem;font-style: italic;}.error-shake {animation: shake 0.5s;}@keyframes shake {0%, 100% { transform: translateX(0); }10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }20%, 40%, 60%, 80% { transform: translateX(5px); }}.content-preview {max-height: 200px;overflow-y: auto;border: 1px solid #e5e7eb;padding: 0.5rem;margin-top: 0.5rem;font-size: 0.875rem;background-color: #f9fafb;}</style></head><body class="bg-gray-50 min-h-screen">1 unmodified line<!-- Header --><header class="text-center mb-8"><h1 class="text-4xl font-bold text-blue-600 mb-2"><i class="fas fa-globe mr-2"></i>Real Web Scraper</h1><p class="text-gray-600">Extract real content from any website</p></header><!-- Main Form --><div class="bg-white rounded-xl shadow-md p-6 mb-8"><div class="mb-6"><label for="url" class="block text-sm font-medium text-gray-700 mb-1"><i class="fas fa-link mr-1"></i> Enter URL to scrape</label><div class="flex"><inputtype="url"id="url"placeholder="https://example.com"class="flex-grow px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-blue-500 focus:border-blue-500"required><buttonid="scrapeBtn"class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-r-lg transition duration-200"><i class="fas fa-download mr-1"></i> Scrape</button></div><p class="mt-1 text-sm text-gray-500">Note: Some websites may block scraping attempts</p></div><!-- Scraping Options --><div class="mb-6"><h3 class="text-lg font-medium text-gray-700 mb-2"><i class="fas fa-cogs mr-1"></i>Scraping Options</h3><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label class="block text-sm font-medium text-gray-700 mb-1">Content to Extract</label><div class="space-y-2"><label class="inline-flex items-center"><input type="checkbox" name="contentType" value="text" class="h-4 w-4 text-blue-600" checked><span class="ml-2 text-gray-700">Text Content</span></label><label class="inline-flex items-center"><input type="checkbox" name="contentType" value="links" class="h-4 w-4 text-blue-600" checked><span class="ml-2 text-gray-700">Links</span></label><label class="inline-flex items-center"><input type="checkbox" name="contentType" value="images" class="h-4 w-4 text-blue-600"><span class="ml-2 text-gray-700">Images</span></label></div></div><div><label class="block text-sm font-medium text-gray-700 mb-1">Output Format</label><div class="space-y-2"><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="json" class="h-4 w-4 text-blue-600" checked><span class="ml-2 text-gray-700">JSON</span></label><label class="inline-flex items-center"><input type="radio" name="outputFormat" value="csv" class="h-4 w-4 text-blue-600"><span class="ml-2 text-gray-700">CSV</span></label></div></div></div></div>1 unmodified line<!-- Loading State --><div id="loading" class="hidden text-center py-8"><div class="loading-spinner mb-4"></div><p class="text-gray-600">Scraping website content...</p><div class="progress-bar mt-4"><div id="progressBarFill" class="progress-bar-fill" style="width: 0%"></div></div><p id="statusMessage" class="status-message">Connecting to website...</p></div><!-- Error Message -->11 unmodified lines</div></div><!-- Results Section --><div id="resultsSection" class="hidden"><div class="flex justify-between items-center mb-4"><h2 class="text-xl font-semibold text-gray-800"><i class="fas fa-file-alt mr-2"></i>Scraped Data7 unmodified lines</button></div></div><!-- Data Preview --><div id="dataPreview" class="mb-6"><div class="flex border-b border-gray-200"><button class="px-4 py-2 font-medium text-sm border-b-2 border-blue-500 text-blue-600" data-tab="preview">Preview</button><button class="px-4 py-2 font-medium text-sm text-gray-500 hover:text-gray-700" data-tab="raw">Raw Data</button></div><div id="previewTab" class="data-tab-content"><div id="textPreview" class="hidden"><h3 class="text-lg font-medium text-gray-700 mt-4 mb-2">Text Content</h3><div class="content-preview" id="textContentPreview"></div></div><div id="linksPreview" class="hidden"><h3 class="text-lg font-medium text-gray-700 mt-4 mb-2">Links</h3><div class="content-preview" id="linksContentPreview"></div></div><div id="imagesPreview" class="hidden"><h3 class="text-lg font-medium text-gray-700 mt-4 mb-2">Images</h3><div class="content-preview" id="imagesContentPreview"></div></div></div><div id="rawTab" class="data-tab-content hidden"><pre id="rawDataOutput" class="overflow-auto max-h-96 text-sm bg-gray-50 p-3 rounded border border-gray-200"></pre></div></div></div></div>6 unmodified lines<div class="grid grid-cols-1 md:grid-cols-3 gap-4"><div class="bg-blue-50 p-4 rounded-lg"><div class="text-blue-600 mb-2"><i class="fas fa-link fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">1. Enter URL</h3><p class="text-sm text-gray-600">Provide any website URL you want to scrape data from.</p></div><div class="bg-purple-50 p-4 rounded-lg"><div class="text-purple-600 mb-2"><i class="fas fa-cog fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">2. Configure</h3><p class="text-sm text-gray-600">Select what content to extract and output format.</p></div><div class="bg-green-50 p-4 rounded-lg"><div class="text-green-600 mb-2"><i class="fas fa-download fa-lg"></i></div><h3 class="font-medium text-gray-800 mb-1">3. Get Data</h3><p class="text-sm text-gray-600">Download or copy the extracted data in your preferred format.</p></div></div></div>3 unmodified linesdocument.addEventListener('DOMContentLoaded', function() {// DOM Elementsconst urlInput = document.getElementById('url');const scrapeBtn = document.getElementById('scrapeBtn');const loading = document.getElementById('loading');const errorContainer = document.getElementById('errorContainer');const errorTitle = document.getElementById('errorTitle');const errorMessage = document.getElementById('errorMessage');const resultsSection = document.getElementById('resultsSection');const progressBarFill = document.getElementById('progressBarFill');const statusMessage = document.getElementById('statusMessage');const copyBtn = document.getElementById('copyBtn');const downloadBtn = document.getElementById('downloadBtn');const rawDataOutput = document.getElementById('rawDataOutput');const textPreview = document.getElementById('textPreview');const textContentPreview = document.getElementById('textContentPreview');const linksPreview = document.getElementById('linksPreview');const linksContentPreview = document.getElementById('linksContentPreview');const imagesPreview = document.getElementById('imagesPreview');const imagesContentPreview = document.getElementById('imagesContentPreview');const tabButtons = document.querySelectorAll('[data-tab]');const tabContents = document.querySelectorAll('.data-tab-content');// Current scraped datalet scrapedData = {};// Tab switchingtabButtons.forEach(button => {button.addEventListener('click', function() {const tabName = this.getAttribute('data-tab');// Update active tab buttontabButtons.forEach(btn => {if (btn === this) {btn.classList.add('border-b-2', 'border-blue-500', 'text-blue-600');btn.classList.remove('text-gray-500', 'hover:text-gray-700');} else {btn.classList.remove('border-b-2', 'border-blue-500', 'text-blue-600');btn.classList.add('text-gray-500', 'hover:text-gray-700');}});// Show/hide tab contenttabContents.forEach(content => {if (content.id === `${tabName}Tab`) {content.classList.remove('hidden');} else {content.classList.add('hidden');}});});});// Update progress bar and status2 unmodified linesstatusMessage.textContent = message;}// Show error messagefunction showError(title, message) {errorTitle.textContent = title;errorMessage.innerHTML = `<p>${message}</p>`;errorContainer.classList.remove('hidden');errorContainer.classList.add('error-shake');setTimeout(() => {errorContainer.classList.remove('error-shake');}, 500);}// Scrape button click handlerscrapeBtn.addEventListener('click', async function() {const url = urlInput.value.trim();// Validate URLif (!url) {showError('Missing URL', 'Please enter a valid URL to scrape.');urlInput.focus();return;}7 unmodified linesreturn;}// Get selected optionsconst contentTypes = Array.from(document.querySelectorAll('input[name="contentType"]:checked')).map(checkbox => checkbox.value);if (contentTypes.length === 0) {showError('No Selection', 'Please select at least one content type to scrape.');return;}const outputFormat = document.querySelector('input[name="outputFormat"]:checked').value;// Show loading stateloading.classList.remove('hidden');errorContainer.classList.add('hidden');resultsSection.classList.add('hidden');// Reset progressupdateProgress(0, 'Initializing scraping process...');try {// Use a proxy to bypass CORS (in a real app, you'd use a backend service)const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;updateProgress(20, 'Fetching website content...');// Fetch the page contentconst response = await fetch(proxyUrl);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();if (!data.contents) {throw new Error('No content received from the website');}updateProgress(40, 'Parsing website content...');// Parse the HTML contentconst parser = new DOMParser();const doc = parser.parseFromString(data.contents, 'text/html');// Extract selected contentscrapedData = {url: url,timestamp: new Date().toISOString()};if (contentTypes.includes('text')) {updateProgress(50, 'Extracting text content...');scrapedData.text = extractTextContent(doc);}if (contentTypes.includes('links')) {updateProgress(60, 'Extracting links...');scrapedData.links = extractLinks(doc);}if (contentTypes.includes('images')) {updateProgress(70, 'Extracting images...');scrapedData.images = extractImages(doc);}updateProgress(90, 'Formatting results...');// Format the output based on selected formatlet formattedData;if (outputFormat === 'json') {formattedData = JSON.stringify(scrapedData, null, 2);} else if (outputFormat === 'csv') {formattedData = convertToCSV(scrapedData);}// Display resultsrawDataOutput.textContent = formattedData;// Update preview tabsupdatePreviewTabs();updateProgress(100, 'Scraping complete!');// Show results after a small delaysetTimeout(() => {loading.classList.add('hidden');resultsSection.classList.remove('hidden');}, 500);} catch (error) {console.error('Scraping error:', error);loading.classList.add('hidden');showError('Scraping Failed', error.message || 'Failed to scrape the website. The site may block scraping attempts.');}});// Extract text content from the pagefunction extractTextContent(doc) {// Remove script and style elementsconst scripts = doc.querySelectorAll('script, style, noscript');scripts.forEach(script => script.remove());// Get all text contentlet text = doc.body.textContent;// Clean up the texttext = text.replace(/\s+/g, ' ').trim();// Split into paragraphs (simple heuristic)const paragraphs = text.split(/\n\s*\n/).filter(p => p.trim().length > 0);return paragraphs;}// Extract links from the pagefunction extractLinks(doc) {const links = [];const linkElements = doc.querySelectorAll('a[href]');linkElements.forEach(link => {const href = link.getAttribute('href');const text = link.textContent.trim();// Skip empty links and javascript linksif (!href || href.startsWith('javascript:')) return;// Make relative URLs absolutelet absoluteUrl;try {absoluteUrl = new URL(href, scrapedData.url).toString();} catch (e) {return; // Skip invalid URLs}links.push({text: text || '[no text]',url: absoluteUrl});});return links;}// Extract images from the pagefunction extractImages(doc) {const images = [];const imgElements = doc.querySelectorAll('img[src]');imgElements.forEach(img => {const src = img.getAttribute('src');const alt = img.getAttribute('alt') || '';// Skip empty srcif (!src) return;// Make relative URLs absolutelet absoluteUrl;try {absoluteUrl = new URL(src, scrapedData.url).toString();} catch (e) {return; // Skip invalid URLs}images.push({src: absoluteUrl,alt: alt});});return images;}// Convert data to CSVfunction convertToCSV(data) {let csv = '';// Handle text contentif (data.text) {csv += '"Text Content"\n';data.text.forEach(paragraph => {csv += `"${paragraph.replace(/"/g, '""')}"\n`;});csv += '\n';}// Handle linksif (data.links) {csv += '"Links","URL"\n';data.links.forEach(link => {csv += `"${link.text.replace(/"/g, '""')}","${link.url}"\n`;});csv += '\n';}// Handle imagesif (data.images) {csv += '"Image URL","Alt Text"\n';data.images.forEach(img => {csv += `"${img.src}","${img.alt.replace(/"/g, '""')}"\n`;});}return csv.trim();}// Update preview tabs with scraped datafunction updatePreviewTabs() {// Text previewif (scrapedData.text) {textContentPreview.innerHTML = scrapedData.text.map(p => `<p class="mb-2">${p}</p>`).join('');textPreview.classList.remove('hidden');} else {textPreview.classList.add('hidden');}// Links previewif (scrapedData.links) {linksContentPreview.innerHTML = scrapedData.links.map(link => `<div class="mb-1"><a href="${link.url}" target="_blank" class="text-blue-600 hover:underline">${link.text}</a><br><span class="text-xs text-gray-500">${link.url}</span></div>`).join('');linksPreview.classList.remove('hidden');} else {linksPreview.classList.add('hidden');}// Images previewif (scrapedData.images) {imagesContentPreview.innerHTML = scrapedData.images.map(img => `<div class="mb-4"><img src="${img.src}" alt="${img.alt}" class="max-w-full h-auto mb-1 border border-gray-200"><div class="text-xs text-gray-600">${img.alt || '[no alt text]'}</div></div>`).join('');imagesPreview.classList.remove('hidden');} else {imagesPreview.classList.add('hidden');}}// Copy button click handlercopyBtn.addEventListener('click', function() {navigator.clipboard.writeText(rawDataOutput.textContent).then(() => {const originalText = copyBtn.innerHTML;copyBtn.innerHTML = '<i class="fas fa-check mr-1"></i>Copied!';setTimeout(() => {copyBtn.innerHTML = originalText;}, 2000);}).catch(err => {showError('Copy Failed', 'Failed to copy text to clipboard.');});});// Download button click handlerdownloadBtn.addEventListener('click', function() {const outputFormat = document.querySelector('input[name="outputFormat"]:checked').value;const data = rawDataOutput.textContent;let mimeType, extension;if (outputFormat === 'json') {mimeType = 'application/json';extension = '.json';} else if (outputFormat === 'csv') {mimeType = 'text/csv';extension = '.csv';}const blob = new Blob([data], { type: mimeType });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;// Create filename based on domain and current datelet domain = 'data';try {const urlObj = new URL(scrapedData.url);domain = urlObj.hostname.replace('www.', '');} catch (e) {}const dateStr = new Date().toISOString().slice(0, 10);a.download = `scraped-${domain}-${dateStr}${extension}`;document.body.appendChild(a);a.click();document.body.removeChild(a);// Revoke the object URL after some time to free up memorysetTimeout(() => {URL.revokeObjectURL(url);}, 100);});});</script><p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Kareem722/web" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
index.html+397-796