Spaces:
Running

web / index.html
Kareem722's picture
Add 1 files
09403c1 verified
Raw History Blame Contribute Delete
32.2 kB
<!DOCTYPE html>
<html lang="en">
<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>
.loading-spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 4px solid #3b82f6;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.progress-bar {
width: 100%;
height: 8px;
background-color: #e5e7eb;
border-radius: 4px;
overflow: hidden;
margin-top: 1rem;
}
.progress-bar-fill {
height: 100%;
background-color: #3b82f6;
transition: width 0.3s ease;
}
.status-message {
font-size: 0.875rem;
color: #4b5563;
margin-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;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.empty-state {
text-align: center;
padding: 2rem;
color: #6b7280;
}
.empty-state i {
font-size: 3rem;
margin-bottom: 1rem;
color: #d1d5db;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-4xl">
<!-- 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">
<input
type="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
value="https://example.com"
>
<button
id="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>
<!-- 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 -->
<div id="errorContainer" class="hidden bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded">
<div class="flex">
<div class="flex-shrink-0">
<i class="fas fa-exclamation-circle text-red-500"></i>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-red-800" id="errorTitle">Error</h3>
<div class="mt-2 text-sm text-red-700" id="errorMessage">
<p>There was an error processing your request.</p>
</div>
</div>
</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 Data
</h2>
<div class="flex gap-2">
<button id="copyBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-1 rounded text-sm">
<i class="fas fa-copy mr-1"></i>Copy
</button>
<button id="downloadBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-download mr-1"></i>Download
</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 tab-button active" data-tab="preview">Preview</button>
<button class="px-4 py-2 font-medium text-sm text-gray-500 hover:text-gray-700 tab-button" data-tab="raw">Raw Data</button>
</div>
<div id="previewTab" class="tab-content active">
<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 id="emptyState" class="empty-state hidden">
<i class="fas fa-folder-open"></i>
<h3 class="text-lg font-medium text-gray-500">No data found</h3>
<p class="text-gray-400">The scraper didn't find any matching content on this page</p>
</div>
</div>
<div id="rawTab" class="tab-content">
<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>
<!-- Help Section -->
<div class="bg-white rounded-xl shadow-md p-6">
<h2 class="text-xl font-semibold text-gray-800 mb-4">
<i class="fas fa-question-circle mr-2"></i>How It Works
</h2>
<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>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const 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 emptyState = document.getElementById('emptyState');
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
// Current scraped data
let scrapedData = {};
// Tab switching
tabButtons.forEach(button => {
button.addEventListener('click', function() {
const tabName = this.getAttribute('data-tab');
// Update active tab button
tabButtons.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 content
tabContents.forEach(content => {
if (content.id === `${tabName}Tab`) {
content.classList.add('active');
} else {
content.classList.remove('active');
}
});
});
});
// Update progress bar and status
function updateProgress(percent, message) {
progressBarFill.style.width = `${percent}%`;
statusMessage.textContent = message;
}
// Show error message
function 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 handler
scrapeBtn.addEventListener('click', async function() {
const url = urlInput.value.trim();
// Validate URL
if (!url) {
showError('Missing URL', 'Please enter a valid URL to scrape.');
urlInput.focus();
return;
}
// Check if URL is valid
try {
new URL(url);
} catch (e) {
showError('Invalid URL', 'Please enter a valid URL including http:// or https://');
urlInput.focus();
return;
}
// Get selected options
const 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 state
loading.classList.remove('hidden');
errorContainer.classList.add('hidden');
resultsSection.classList.add('hidden');
// Reset progress
updateProgress(0, 'Initializing scraping process...');
try {
// Use a CORS proxy to bypass restrictions
// Note: In production, you should use your own backend service for this
const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;
updateProgress(20, 'Fetching website content...');
// Fetch the page content through proxy
const response = await fetch(proxyUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Try to parse as JSON first
let data;
try {
data = await response.json();
} catch (jsonError) {
// If JSON parsing fails, try to get the raw text
const text = await response.text();
// Check if this is a JSONP response
if (text.startsWith('/**/') || text.startsWith('typeof') || text.includes('callback(')) {
throw new Error('The website returned a JSONP response instead of HTML. Try a different URL.');
}
// Treat as raw HTML
data = { contents: text };
}
if (!data.contents) {
throw new Error('No content received from the website. It may block scraping attempts.');
}
updateProgress(40, 'Parsing website content...');
// Create a temporary DOM element to parse the HTML
const parser = new DOMParser();
const doc = parser.parseFromString(data.contents, 'text/html');
// Extract selected content
scrapedData = {
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 format
let formattedData;
if (outputFormat === 'json') {
formattedData = JSON.stringify(scrapedData, null, 2);
} else if (outputFormat === 'csv') {
formattedData = convertToCSV(scrapedData);
}
// Display results
rawDataOutput.textContent = formattedData;
// Update preview tabs
updatePreviewTabs();
updateProgress(100, 'Scraping complete!');
// Show results after a small delay
setTimeout(() => {
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 or the proxy service may be unavailable.');
}
});
// Extract text content from the page
function extractTextContent(doc) {
// Clone the document to avoid modifying the original
const docClone = doc.cloneNode(true);
// Remove unwanted elements
const unwantedElements = docClone.querySelectorAll('script, style, noscript, iframe, svg, img');
unwantedElements.forEach(el => el.remove());
// Get all text content
let text = docClone.body.textContent;
// Clean up the text
text = 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.slice(0, 50); // Limit to first 50 paragraphs
}
// Extract links from the page
function 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 links
if (!href || href.startsWith('javascript:')) return;
// Make relative URLs absolute
let absoluteUrl;
try {
absoluteUrl = new URL(href, scrapedData.url).toString();
} catch (e) {
return; // Skip invalid URLs
}
// Skip duplicate links
if (links.some(l => l.url === absoluteUrl)) return;
links.push({
text: text || '[no text]',
url: absoluteUrl
});
});
return links.slice(0, 50); // Limit to first 50 links
}
// Extract images from the page
function 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 src
if (!src) return;
// Make relative URLs absolute
let absoluteUrl;
try {
absoluteUrl = new URL(src, scrapedData.url).toString();
} catch (e) {
return; // Skip invalid URLs
}
// Skip duplicate images
if (images.some(i => i.src === absoluteUrl)) return;
images.push({
src: absoluteUrl,
alt: alt
});
});
return images.slice(0, 20); // Limit to first 20 images
}
// Convert data to CSV
function convertToCSV(data) {
let csv = '';
// Handle text content
if (data.text && data.text.length > 0) {
csv += '"Text Content"\n';
data.text.forEach(paragraph => {
csv += `"${paragraph.replace(/"/g, '""')}"\n`;
});
csv += '\n';
}
// Handle links
if (data.links && data.links.length > 0) {
csv += '"Link Text","URL"\n';
data.links.forEach(link => {
csv += `"${link.text.replace(/"/g, '""')}","${link.url}"\n`;
});
csv += '\n';
}
// Handle images
if (data.images && data.images.length > 0) {
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 data
function updatePreviewTabs() {
let hasData = false;
// Text preview
if (scrapedData.text && scrapedData.text.length > 0) {
textContentPreview.innerHTML = scrapedData.text
.map(p => `<p class="mb-2">${p}</p>`)
.join('');
textPreview.classList.remove('hidden');
hasData = true;
} else {
textPreview.classList.add('hidden');
}
// Links preview
if (scrapedData.links && scrapedData.links.length > 0) {
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');
hasData = true;
} else {
linksPreview.classList.add('hidden');
}
// Images preview
if (scrapedData.images && scrapedData.images.length > 0) {
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');
hasData = true;
} else {
imagesPreview.classList.add('hidden');
}
// Show empty state if no data found
if (!hasData) {
emptyState.classList.remove('hidden');
} else {
emptyState.classList.add('hidden');
}
}
// Copy button click handler
copyBtn.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 handler
downloadBtn.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 date
let 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 memory
setTimeout(() => {
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>
</html>