Creating a comprehensive Tampermonkey script with the features you've described is a substantial project. Below is a foundational script that incorporates many of your requirements. Due to the complexity and size, this script focuses on essential functionalities, which you can further expand upon.
Please Note: Web scraping should always respect the target website's robots.txt and terms of service. Ensure you have permission to scrape the sites you're targeting to avoid legal issues.
Tampermonkey Script: Advanced Web Crawler with UI
// ==UserScript==
// @name Advanced Web Crawler
// @namespace http://tampermonkey.net/
// @version 1.0
// @description An advanced web crawler with UI, logging, and data management features.
// @author Your Name
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addStyle
// @connect *
// ==/UserScript==
(function() {
'use strict';
// Configuration
const CONFIG = {
delayBetweenRequests: 3000, // 3 seconds
maxRetries: 3,
blacklist: [], // Add blacklisted domains here
whitelist: [], // If whitelist is not empty, only these domains are crawled
keyboardShortcuts: {
save: 'ctrl+s',
start: 'ctrl+p',
stop: 'ctrl+q',
downloadCSV: 'ctrl+d',
downloadJSON: 'ctrl+j',
activateTab1: 'ctrl+1',
activateTab2: 'ctrl+2',
activateTab3: 'ctrl+3'
}
};
// State Variables
let isCrawling = false;
let currentPage = 1;
let currentSiteIndex = 0;
let collectedData = [];
let visitedUrls = new Set();
let totalSites = 0;
let processedSites = 0;
// Initialize UI
initUI();
// Add Keyboard Shortcuts
addKeyboardShortcuts();
// Functions
function initUI() {
// Create UI Container
const container = document.createElement('div');
container.id = 'crawler-container';
container.style.position = 'fixed';
container.style.top = '10px';
container.style.right = '10px';
container.style.width = '400px';
container.style.height = '600px';
container.style.backgroundColor = '#f9f9f9';
container.style.border = '1px solid #ccc';
container.style.zIndex = '10000';
container.style.boxShadow = '0 0 10px rgba(0,0,0,0.1)';
container.style.fontFamily = 'Arial, sans-serif';
container.style.display = 'flex';
container.style.flexDirection = 'column';
container.style.resize = 'both';
container.style.overflow = 'hidden';
// Tab Menu
const tabMenu = document.createElement('div');
tabMenu.id = 'tab-menu';
tabMenu.style.display = 'flex';
tabMenu.style.borderBottom = '1px solid #ccc';
tabMenu.style.backgroundColor = '#eee';
const tabs = [
{ name: 'Logs', icon: '📜', shortcut: 'Ctrl+1' },
{ name: 'Data', icon: '📊', shortcut: 'Ctrl+2' },
{ name: 'Settings', icon: '⚙️', shortcut: 'Ctrl+3' }
];
tabs.forEach((tab, index) => {
const tabElement = document.createElement('div');
tabElement.className = 'tab';
tabElement.innerHTML = `${tab.icon} ${tab.name}`;
tabElement.style.flex = '1';
tabElement.style.padding = '10px';
tabElement.style.cursor = 'pointer';
tabElement.style.textAlign = 'center';
tabElement.dataset.tab = `tab-${index + 1}`;
tabElement.title = `Press ${tab.shortcut} to activate`;
tabElement.addEventListener('click', () => activateTab(index + 1));
tabMenu.appendChild(tabElement);
});
container.appendChild(tabMenu);
// Tab Contents
const tabContents = document.createElement('div');
tabContents.id = 'tab-contents';
tabContents.style.flex = '1';
tabContents.style.display = 'flex';
tabContents.style.flexDirection = 'column';
// Logs Tab
const logTab = document.createElement('div');
logTab.id = 'tab-1';
logTab.style.flex = '1';
logTab.style.padding = '10px';
logTab.style.overflowY = 'auto';
logTab.style.display = 'none';
tabContents.appendChild(logTab);
// Data Tab
const dataTab = document.createElement('div');
dataTab.id = 'tab-2';
dataTab.style.flex = '1';
dataTab.style.padding = '10px';
dataTab.style.overflowY = 'auto';
dataTab.style.display = 'none';
// Search Field
const searchField = document.createElement('input');
searchField.type = 'text';
searchField.placeholder = 'Search...';
searchField.style.width = '100%';
searchField.style.padding = '5px';
searchField.addEventListener('input', filterTable);
dataTab.appendChild(searchField);
// Data Table
const table = document.createElement('table');
table.id = 'data-table';
table.style.width = '100%';
table.style.borderCollapse = 'collapse';
table.style.marginTop = '10px';
const header = table.insertRow();
['Site Name', 'URL', 'Description', 'Category'].forEach(text => {
const th = document.createElement('th');
th.innerText = text;
th.style.border = '1px solid #ccc';
th.style.padding = '5px';
th.style.backgroundColor = '#f2f2f2';
table.appendChild(header);
});
dataTab.appendChild(table);
tabContents.appendChild(dataTab);
// Settings Tab
const settingsTab = document.createElement('div');
settingsTab.id = 'tab-3';
settingsTab.style.flex = '1';
settingsTab.style.padding = '10px';
settingsTab.style.overflowY = 'auto';
settingsTab.style.display = 'none';
// Delay Setting
const delayLabel = document.createElement('label');
delayLabel.innerText = 'Delay Between Requests (ms): ';
const delayInput = document.createElement('input');
delayInput.type = 'number';
delayInput.value = CONFIG.delayBetweenRequests;
delayInput.id = 'delay-input';
delayInput.style.width = '100%';
delayInput.title = 'Set delay between requests to avoid overloading servers';
settingsTab.appendChild(delayLabel);
settingsTab.appendChild(delayInput);
// Blacklist
const blacklistLabel = document.createElement('label');
blacklistLabel.innerText = 'Blacklist Domains (comma separated): ';
const blacklistInput = document.createElement('input');
blacklistInput.type = 'text';
blacklistInput.value = CONFIG.blacklist.join(',');
blacklistInput.id = 'blacklist-input';
blacklistInput.style.width = '100%';
blacklistInput.title = 'Domains to exclude from crawling';
settingsTab.appendChild(document.createElement('br'));
settingsTab.appendChild(blacklistLabel);
settingsTab.appendChild(blacklistInput);
// Whitelist
const whitelistLabel = document.createElement('label');
whitelistLabel.innerText = 'Whitelist Domains (comma separated): ';
const whitelistInput = document.createElement('input');
whitelistInput.type = 'text';
whitelistInput.value = CONFIG.whitelist.join(',');
whitelistInput.id = 'whitelist-input';
whitelistInput.style.width = '100%';
whitelistInput.title = 'If set, only these domains will be crawled';
settingsTab.appendChild(document.createElement('br'));
settingsTab.appendChild(whitelistLabel);
settingsTab.appendChild(whitelistInput);
// Save Settings Button
const saveButton = document.createElement('button');
saveButton.innerText = 'Save Settings';
saveButton.style.marginTop = '10px';
saveButton.addEventListener('click', saveSettings);
settingsTab.appendChild(saveButton);
tabContents.appendChild(settingsTab);
container.appendChild(tabContents);
// Progress Bar
const progressBarContainer = document.createElement('div');
progressBarContainer.style.width = '100%';
progressBarContainer.style.height = '20px';
progressBarContainer.style.backgroundColor = '#ddd';
progressBarContainer.style.marginTop = '10px';
const progressBar = document.createElement('div');
progressBar.id = 'progress-bar';
progressBar.style.width = '0%';
progressBar.style.height = '100%';
progressBar.style.backgroundColor = '#4caf50';
progressBar.style.textAlign = 'center';
progressBar.style.color = 'white';
progressBar.innerText = '0%';
progressBarContainer.appendChild(progressBar);
container.appendChild(progressBarContainer);
// Control Buttons
const controls = document.createElement('div');
controls.style.display = 'flex';
controls.style.justifyContent = 'space-around';
controls.style.marginTop = '10px';
const startButton = document.createElement('button');
startButton.innerText = 'Start Crawling (Ctrl+P)';
startButton.title = 'Start the crawling process';
startButton.addEventListener('click', startCrawling);
controls.appendChild(startButton);
const stopButton = document.createElement('button');
stopButton.innerText = 'Stop Crawling (Ctrl+Q)';
stopButton.title = 'Stop the crawling process';
stopButton.addEventListener('click', stopCrawling);
controls.appendChild(stopButton);
container.appendChild(controls);
// Append Container to Body
document.body.appendChild(container);
// Activate Logs Tab by Default
activateTab(1);
}
function activateTab(tabNumber) {
// Hide all tabs
['tab-1', 'tab-2', 'tab-3'].forEach(id => {
document.getElementById(id).style.display = 'none';
});
// Remove active style from all tab buttons
document.querySelectorAll('.tab').forEach(tab => {
tab.style.backgroundColor = '#eee';
});
// Show selected tab
document.getElementById(`tab-${tabNumber}`).style.display = 'block';
// Highlight active tab
document.querySelector(`.tab[data-tab="tab-${tabNumber}"]`).style.backgroundColor = '#fff';
}
function addKeyboardShortcuts() {
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
saveSettings();
}
if (e.ctrlKey && e.key === 'p') {
e.preventDefault();
startCrawling();
}
if (e.ctrlKey && e.key === 'q') {
e.preventDefault();
stopCrawling();
}
if (e.ctrlKey && e.key === 'd') {
e.preventDefault();
downloadCSV();
}
if (e.ctrlKey && e.key === 'j') {
e.preventDefault();
downloadJSON();
}
if (e.ctrlKey && e.key === '1') {
e.preventDefault();
activateTab(1);
}
if (e.ctrlKey && e.key === '2') {
e.preventDefault();
activateTab(2);
}
if (e.ctrlKey && e.key === '3') {
e.preventDefault();
activateTab(3);
}
});
}
function saveSettings() {
const delay = document.getElementById('delay-input').value;
const blacklist = document.getElementById('blacklist-input').value.split(',').map(s => s.trim()).filter(s => s);
const whitelist = document.getElementById('whitelist-input').value.split(',').map(s => s.trim()).filter(s => s);
CONFIG.delayBetweenRequests = parseInt(delay) || CONFIG.delayBetweenRequests;
CONFIG.blacklist = blacklist;
CONFIG.whitelist = whitelist;
log('Settings saved.');
}
function log(message, type = 'info') {
const logTab = document.getElementById('tab-1');
const entry = document.createElement('div');
entry.innerText = `[${new Date().toLocaleTimeString()}] [${type.toUpperCase()}] ${message}`;
if (type === 'error') {
entry.style.color = 'red';
}
logTab.appendChild(entry);
logTab.scrollTop = logTab.scrollHeight;
}
function startCrawling() {
if (isCrawling) {
log('Crawling is already in progress.', 'error');
return;
}
isCrawling = true;
collectedData = [];
visitedUrls = new Set();
currentPage = 1;
currentSiteIndex = 0;
processedSites = 0;
log('Crawling started.');
crawl();
}
function stopCrawling() {
if (!isCrawling) {
log('Crawling is not running.', 'error');
return;
}
isCrawling = false;
log('Crawling stopped.');
}
async function crawl() {
while (isCrawling) {
log(`Navigating to page ${currentPage}...`);
// Replace the following line with the actual URL structure of your target website.
const searchUrl = `https://www.example.com/search?q=your_query&page=${currentPage}`;
try {
const response = await fetch(searchUrl);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Extract search results - Modify selectors based on the target website's structure
const results = doc.querySelectorAll('.search-result');
if (results.length === 0) {
log('No more results found. Crawling completed.');
break;
}
totalSites += results.length;
for (let i = 0; i < results.length; i++) {
if (!isCrawling) break;
const result = results[i];
const siteName = result.querySelector('.site-name')?.innerText.trim() || 'N/A';
const siteUrl = result.querySelector('a')?.href || 'N/A';
const siteDescription = result.querySelector('.description')?.innerText.trim() || 'N/A';
// Duplicate Check
if (visitedUrls.has(siteUrl)) {
log(`Duplicate found: ${siteUrl}`, 'info');
continue;
}
visitedUrls.add(siteUrl);
// Blacklist/Whitelist Check
const domain = (new URL(siteUrl)).hostname;
if (CONFIG.whitelist.length > 0 && !CONFIG.whitelist.includes(domain)) {
log(`Domain not in whitelist: ${domain}`, 'info');
continue;
}
if (CONFIG.blacklist.includes(domain)) {
log(`Domain is blacklisted: ${domain}`, 'info');
continue;
}
// Fetch Site Content
try {
const siteResponse = await fetch(siteUrl);
if (!siteResponse.ok) throw new Error(`Failed to fetch ${siteUrl}`);
const siteHtml = await siteResponse.text();
const siteDoc = parser.parseFromString(siteHtml, 'text/html');
const textContent = siteDoc.body.innerText || 'N/A';
// Content Quality Evaluation
const qualityScore = evaluateContentQuality(textContent);
// Keyword Classification
const category = classifyKeywords(siteDescription);
collectedData.push({
siteName,
siteUrl,
siteDescription,
textContent,
htmlContent: siteHtml,
category,
qualityScore
});
processedSites++;
updateProgress();
// Update Data Table
addToTable(siteName, siteUrl, siteDescription, category);
log(`Processed: ${siteName}`);
} catch (siteError) {
log(`Error fetching ${siteUrl}: ${siteError.message}`, 'error');
}
// Delay Between Requests
await delay(CONFIG.delayBetweenRequests);
}
// Move to Next Page
currentPage++;
updateProgress();
} catch (error) {
log(`Error on page ${currentPage}: ${error.message}`, 'error');
break;
}
}
isCrawling = false;
log('Crawling process has ended.');
}
function evaluateContentQuality(text) {
const wordCount = text.split(/\s+/).length;
let score = 0;
if (wordCount > 500) score += 1;
if (wordCount > 1000) score += 1;
// Add more criteria as needed
return score;
}
function classifyKeywords(description) {
const keywords = {
'technology': ['tech', 'software', 'hardware', 'computer'],
'education': ['learning', 'education', 'school', 'university'],
'entertainment': ['movie', 'music', 'game', 'entertainment'],
// Add more categories and keywords as needed
};
for (const [category, keys] of Object.entries(keywords)) {
for (const key of keys) {
if (description.toLowerCase().includes(key)) {
return category;
}
}
}
return 'uncategorized';
}
function addToTable(name, url, description, category) {
const table = document.getElementById('data-table');
const row = table.insertRow();
[name, url, description, category].forEach((text, index) => {
const cell = row.insertCell();
cell.innerText = text;
cell.style.border = '1px solid #ccc';
cell.style.padding = '5px';
// Add tooltip for cells
cell.title = text;
});
// Add click event to URL cell to view HTML content
row.cells[1].style.color = 'blue';
row.cells[1].style.textDecoration = 'underline';
row.cells[1].style.cursor = 'pointer';
row.cells[1].addEventListener('click', () => {
showModal(collectedData.find(data => data.siteUrl === url).htmlContent);
});
}
function showModal(htmlContent) {
// Create Modal
const modal = document.createElement('div');
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
modal.style.display = 'flex';
modal.style.justifyContent = 'center';
modal.style.alignItems = 'center';
modal.style.zIndex = '10001';
const modalContent = document.createElement('div');
modalContent.style.width = '80%';
modalContent.style.height = '80%';
modalContent.style.backgroundColor = '#fff';
modalContent.style.overflowY = 'auto';
modalContent.style.padding = '20px';
modalContent.innerHTML = htmlContent;
modal.appendChild(modalContent);
// Close Modal on Click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
document.body.removeChild(modal);
}
});
document.body.appendChild(modal);
}
function updateProgress() {
const progressBar = document.getElementById('progress-bar');
const percent = totalSites ? Math.min((processedSites / totalSites) * 100, 100) : 0;
progressBar.style.width = `${percent}%`;
progressBar.innerText = `${Math.floor(percent)}%`;
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function filterTable() {
const keyword = this.value.toLowerCase();
const table = document.getElementById('data-table');
for (let i = 1; i < table.rows.length; i++) {
const row = table.rows[i];
let match = false;
for (let j = 0; j < row.cells.length; j++) {
const cellText = row.cells[j].innerText.toLowerCase();
if (cellText.includes(keyword)) {
match = true;
break;
}
}
row.style.display = match ? '' : 'none';
}
}
function downloadCSV() {
let csvContent = "data:text/csv;charset=utf-8,Site Name,URL,Description,Category,Quality Score\n";
collectedData.forEach(row => {
const rowArray = [row.siteName, row.siteUrl, row.siteDescription, row.category, row.qualityScore];
const rowString = rowArray.map(item => `"${item.replace(/"/g, '""')}"`).join(',');
csvContent += rowString + "\n";
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "crawled_data.csv");
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link);
log('CSV downloaded.');
}
function downloadJSON() {
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(collectedData, null, 2));
const link = document.createElement("a");
link.setAttribute("href", dataStr);
link.setAttribute("download", "crawled_data.json");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
log('JSON downloaded.');
}
})();
Explanation of the Script
-
Metadata Block: Defines the Tampermonkey script's name, namespace, version, description, author, match patterns, and permissions.
-
Configuration Object (CONFIG): Stores settings like delay between requests, retry attempts, blacklist/whitelist domains, and keyboard shortcuts.
-
State Variables: Keep track of the crawling state, such as whether crawling is active, current page, processed sites, and collected data.
-
UI Initialization (initUI):
- Container: A fixed-positioned container on the webpage to hold the crawler's UI.
- Tab Menu: Three tabs for Logs, Data, and Settings, each with icons and titles for tooltips.
- Tab Contents:
- Logs Tab: Displays real-time logs of the crawling process.
- Data Tab: Contains a search field and a table to display crawled data.
- Settings Tab: Allows users to adjust crawling settings like delay, blacklist, and whitelist.
- Progress Bar: Visual representation of the crawling progress.
- Control Buttons: Buttons to start and stop the crawling process, with associated keyboard shortcuts.
-
Keyboard Shortcuts (addKeyboardShortcuts): Allows users to interact with the crawler using keyboard combinations, enhancing usability.
-
Crawling Functions:
startCrawling: Initializes and starts the crawling process.
stopCrawling: Stops the crawling process gracefully.
crawl: Core function that fetches search result pages, iterates through each result, fetches individual site content, evaluates content quality, classifies keywords, and stores the data.
evaluateContentQuality: Simple function to assign a quality score based on word count. This can be expanded with more sophisticated metrics.
classifyKeywords: Categorizes sites based on predefined keywords in descriptions.
addToTable: Adds the crawled data to the Data tab's table, including interactivity to view full HTML content in a modal.
Enhancements and Additional Features
While the script above covers many of your requirements, here are some suggestions for further enhancements:
-
Error Handling Enhancements:
- Implement retry logic for failed requests up to
CONFIG.maxRetries.
- Categorize errors more specifically (e.g., network errors, parsing errors).
-
Advanced UI Improvements:
- Implement a responsive and more sophisticated design using CSS frameworks or libraries.
- Add pagination controls to navigate through crawled data within the Data tab.
- Enhance the progress bar with more details like estimated time remaining.
-
Content Quality Evaluation:
- Integrate Natural Language Processing (NLP) techniques to better assess content quality.
- Use sentiment analysis or topic modeling for richer classifications.
-
Keyword Classification Enhancements:
- Allow users to define their own categories and keywords via the Settings tab.
- Implement machine learning models for dynamic classification.
-
Performance Optimization:
- Utilize asynchronous processing and batching to speed up the crawling process.
- Store visited URLs and collected data using
GM_setValue and GM_getValue to persist data across sessions.
-
User Experience Improvements:
- Add notifications or alerts for significant events (e.g., completion, errors).
- Implement drag-and-drop or resizable columns in the data table for better usability.
-
Security Considerations:
- Sanitize and validate all fetched data to prevent potential security vulnerabilities, especially when displaying HTML content.
Final Thoughts
Developing such a comprehensive crawler involves careful consideration of ethical guidelines, respect for website terms of service, and optimization for performance and scalability. The provided script serves as a solid foundation, and with iterative improvements, you can tailor it to meet all your educational and functional needs.
Remember to thoroughly test the script in controlled environments before deploying it widely to ensure it behaves as expected and adheres to all legal and ethical standards.