// ==UserScript==
// @name Advanced Web Crawler
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Comprehensive web crawler with advanced features
// @author Your Name
// @match *://*/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @connect *
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
///////////////////////
// Configuration
///////////////////////
const config = {
crawlDelay: 3000, // in milliseconds
maxRetries: 3,
maxPages: 100,
blacklist: GM_getValue('blacklist', []),
whitelist: GM_getValue('whitelist', []),
};
///////////////////////
// UI Creation
///////////////////////
// Create main container
const container = $('<div>', {
id: 'crawler-container',
css: {
position: 'fixed',
top: '10px',
right: '10px',
width: '400px',
height: '600px',
background: '#f9f9f9',
border: '1px solid #ccc',
'z-index': 10000,
'font-family': 'Arial, sans-serif',
'box-shadow': '0 0 10px rgba(0,0,0,0.5)',
'border-radius': '5px',
'overflow': 'hidden',
}
}).appendTo('body');
// Create tabs
const tabs = $('<div>', {
id: 'crawler-tabs',
css: {
display: 'flex',
'background-color': '#ddd',
cursor: 'pointer',
}
}).appendTo(container);
const tabNames = ['📜 로그', '📊 데이터', '⚙️ 설정'];
tabNames.forEach((name, index) => {
$('<div>', {
text: name,
class: 'crawler-tab',
'data-tab': `tab-${index+1}`,
css: {
padding: '10px',
flex: 1,
'text-align': 'center',
'border-right': index < tabNames.length - 1 ? '1px solid #ccc' : 'none',
'background-color': index === 0 ? '#fff' : '#ddd',
'font-weight': index === 0 ? 'bold' : 'normal',
}
}).appendTo(tabs);
});
// Create tab contents
const tabContents = $('<div>', {
id: 'crawler-tab-contents',
css: {
padding: '10px',
height: '550px',
overflow: 'auto',
background: '#fff',
display: 'block',
}
}).appendTo(container);
// Log Tab
const logTab = $('<div>', {
id: 'tab-1',
css: {
display: 'block',
}
}).appendTo(tabContents);
// Data Tab
const dataTab = $('<div>', {
id: 'tab-2',
css: {
display: 'none',
}
}).appendTo(tabContents);
// Settings Tab
const settingsTab = $('<div>', {
id: 'tab-3',
css: {
display: 'none',
}
}).appendTo(tabContents);
// Populate Log Tab
$('<h3>', { text: '로그' }).appendTo(logTab);
const logArea = $('<div>', {
id: 'crawler-log',
css: {
'max-height': '500px',
overflow: 'auto',
'background-color': '#f0f0f0',
padding: '10px',
'border-radius': '5px',
'font-size': '12px',
}
}).appendTo(logTab);
// Populate Data Tab
$('<h3>', { text: '데이터' }).appendTo(dataTab);
const searchInput = $('<input>', {
type: 'text',
placeholder: '검색...',
css: {
width: '100%',
padding: '5px',
'margin-bottom': '10px',
'box-sizing': 'border-box',
},
title: '키워드로 데이터 필터링'
}).appendTo(dataTab);
const dataTable = $('<table>', {
id: 'crawler-data-table',
css: {
width: '100%',
'border-collapse': 'collapse',
}
}).appendTo(dataTab);
const tableHeader = $('<tr>').appendTo(dataTable);
['사이트 이름', '주소', '설명', 'HTML 내용'].forEach(header => {
$('<th>', {
text: header,
css: {
border: '1px solid #ccc',
padding: '5px',
'background-color': '#eee',
}
}).appendTo(tableHeader);
});
// Populate Settings Tab
$('<h3>', { text: '설정' }).appendTo(settingsTab);
const settingsForm = $('<div>').appendTo(settingsTab);
// Blacklist
$('<label>', { text: '🚫 블랙리스트 도메인 (콤마로 구분):' }).appendTo(settingsForm);
const blacklistInput = $('<input>', {
type: 'text',
id: 'crawler-blacklist',
value: config.blacklist.join(','),
css: { width: '100%', padding: '5px', 'margin-bottom': '10px', 'box-sizing': 'border-box' },
title: '크롤링에서 제외할 도메인 목록'
}).appendTo(settingsForm);
// Whitelist
$('<label>', { text: '✅ 화이트리스트 도메인 (콤마로 구분):' }).appendTo(settingsForm);
const whitelistInput = $('<input>', {
type: 'text',
id: 'crawler-whitelist',
value: config.whitelist.join(','),
css: { width: '100%', padding: '5px', 'margin-bottom': '10px', 'box-sizing': 'border-box' },
title: '크롤링을 허용할 도메인 목록'
}).appendTo(settingsForm);
// Crawl Delay
$('<label>', { text: '크롤링 딜레이 (밀리초):' }).appendTo(settingsForm);
const crawlDelayInput = $('<input>', {
type: 'number',
id: 'crawler-delay',
value: config.crawlDelay,
css: { width: '100%', padding: '5px', 'margin-bottom': '10px', 'box-sizing': 'border-box' },
title: '크롤링 요청 간 딜레이 시간'
}).appendTo(settingsForm);
// Max Retries
$('<label>', { text: '최대 재시도 횟수:' }).appendTo(settingsForm);
const maxRetriesInput = $('<input>', {
type: 'number',
id: 'crawler-max-retries',
value: config.maxRetries,
css: { width: '100%', padding: '5px', 'margin-bottom': '10px', 'box-sizing': 'border-box' },
title: '요청 실패 시 재시도할 최대 횟수'
}).appendTo(settingsForm);
// Save Settings Button
$('<button>', {
text: '설정 저장',
css: {
padding: '10px',
width: '100%',
'background-color': '#4CAF50',
color: '#fff',
border: 'none',
'border-radius': '5px',
cursor: 'pointer',
},
title: '설정을 저장합니다.'
}).on('click', saveSettings).appendTo(settingsForm);
///////////////////////
// Controls
///////////////////////
const controls = $('<div>', {
id: 'crawler-controls',
css: {
padding: '10px',
'background-color': '#eee',
'border-bottom': '1px solid #ccc',
}
}).prependTo(container);
// Start Button
$('<button>', {
text: '시작',
id: 'crawler-start',
css: {
padding: '5px 10px',
margin: '0 5px',
cursor: 'pointer',
},
title: '크롤링을 시작합니다.'
}).on('click', startCrawling).appendTo(controls);
// Stop Button
$('<button>', {
text: '중지',
id: 'crawler-stop',
css: {
padding: '5px 10px',
margin: '0 5px',
cursor: 'pointer',
},
title: '현재 크롤링을 중지합니다.'
}).on('click', stopCrawling).appendTo(controls);
// Reset Button
$('<button>', {
text: '초기화',
id: 'crawler-reset',
css: {
padding: '5px 10px',
margin: '0 5px',
cursor: 'pointer',
},
title: '크롤링 데이터를 초기화합니다.'
}).on('click', resetCrawling).appendTo(controls);
// Progress Bar
const progressBarContainer = $('<div>', {
css: {
width: '100%',
background: '#ddd',
borderRadius: '5px',
overflow: 'hidden',
marginTop: '10px',
}
}).appendTo(controls);
const progressBar = $('<div>', {
id: 'crawler-progress-bar',
css: {
width: '0%',
height: '10px',
background: '#4CAF50',
}
}).appendTo(progressBarContainer);
// Progress Percentage
const progressPercent = $('<div>', {
id: 'crawler-progress-percent',
text: '0%',
css: {
'text-align': 'center',
'font-size': '12px',
marginTop: '5px',
}
}).appendTo(controls);
///////////////////////
// Crawler Logic
///////////////////////
let isCrawling = false;
let crawlQueue = [];
let crawledData = [];
let visitedUrls = new Set();
let retries = {};
// Keyboard Shortcuts
$(document).on('keydown', function(e) {
if (e.ctrlKey && e.key === '1') {
switchTab(1);
} else if (e.ctrlKey && e.key === '2') {
switchTab(2);
} else if (e.ctrlKey && e.key === '3') {
switchTab(3);
} else if (e.ctrlKey && e.key === 'P') {
startCrawling();
} else if (e.ctrlKey && e.key === 'Q') {
stopCrawling();
} else if (e.ctrlKey && e.key === 'S') {
saveSettings();
} else if (e.ctrlKey && e.key === 'D') {
downloadCSV();
} else if (e.ctrlKey && e.key === 'J') {
downloadJSON();
}
});
// Switch Tab Function
function switchTab(tabNumber) {
$('.crawler-tab').css({'background-color': '#ddd', 'font-weight': 'normal'});
$(`.crawler-tab[data-tab="tab-${tabNumber}"]`).css({'background-color': '#fff', 'font-weight': 'bold'});
$('#crawler-tab-contents > div').hide();
$(`#tab-${tabNumber}`).show();
}
// Save Settings Function
function saveSettings() {
config.blacklist = $('#crawler-blacklist').val().split(',').map(s => s.trim()).filter(s => s);
config.whitelist = $('#crawler-whitelist').val().split(',').map(s => s.trim()).filter(s => s);
config.crawlDelay = parseInt($('#crawler-delay').val()) || 3000;
config.maxRetries = parseInt($('#crawler-max-retries').val()) || 3;
GM_setValue('blacklist', config.blacklist);
GM_setValue('whitelist', config.whitelist);
log('설정이 저장되었습니다.');
}
// Start Crawling Function
function startCrawling() {
if (isCrawling) {
log('이미 크롤링이 진행 중입니다.');
return;
}
const query = prompt('검색어를 입력하세요:');
if (!query) {
log('검색어가 입력되지 않았습니다.');
return;
}
isCrawling = true;
log(`크롤링 시작: "${query}"`);
enqueueUrls(generateSearchUrls(query));
processQueue();
}
// Stop Crawling Function
function stopCrawling() {
if (!isCrawling) {
log('크롤링이 진행되고 있지 않습니다.');
return;
}
isCrawling = false;
log('크롤링이 중지되었습니다.');
}
// Reset Crawling Function
function resetCrawling() {
if (isCrawling) {
stopCrawling();
}
crawlQueue = [];
crawledData = [];
visitedUrls.clear();
updateDataTable();
log('크롤링 데이터가 초기화되었습니다.');
updateProgress(0);
}
// Enqueue URLs
function enqueueUrls(urls) {
crawlQueue = crawlQueue.concat(urls);
}
// Generate Search URLs (Placeholder Function)
function generateSearchUrls(query) {
// Implement actual search URL generation based on the target website
// For demonstration, we'll assume a generic search URL with pagination
const urls = [];
const totalPages = 5; // Example: 5 pages
for (let i = 1; i <= totalPages; i++) {
urls.push(`https://www.example.com/search?q=${encodeURIComponent(query)}&page=${i}`);
}
return urls;
}
// Process Crawl Queue
async function processQueue() {
while (isCrawling && crawlQueue.length > 0) {
const url = crawlQueue.shift();
if (shouldSkipUrl(url)) {
log(`스킵된 URL: ${url}`);
continue;
}
if (visitedUrls.has(url)) {
log(`이미 방문한 URL: ${url}`);
continue;
}
try {
log(`크롤링 중: ${url}`);
const response = await fetchPage(url);
const extractedData = extractDataFromPage(response, url);
crawledData.push(...extractedData);
updateDataTable();
visitedUrls.add(url);
updateProgress((crawledData.length / config.maxPages) * 100);
// Enqueue next set of URLs if needed
// ...
} catch (error) {
log(`에러 발생: ${error} (URL: ${url})`);
if (!retries[url]) {
retries[url] = 0;
}
if (retries[url] < config.maxRetries) {
retries[url]++;
crawlQueue.push(url);
log(`재시도 (${retries[url]}): ${url}`);
} else {
log(`최대 재시도 횟수 초과: ${url}`);
}
}
await delay(config.crawlDelay);
}
if (crawlQueue.length === 0) {
isCrawling = false;
log('크롤링이 완료되었습니다.');
}
}
// Check if URL should be skipped based on blacklist/whitelist
function shouldSkipUrl(url) {
const hostname = new URL(url).hostname;
if (config.whitelist.length > 0 && !config.whitelist.some(domain => hostname.includes(domain))) {
return true;
}
if (config.blacklist.some(domain => hostname.includes(domain))) {
return true;
}
return false;
}
// Fetch Page Content
function fetchPage(url) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: function(response) {
if (response.status === 200) {
resolve(response.responseText);
} else {
reject(`HTTP ${response.status}`);
}
},
onerror: function(err) {
reject('네트워크 에러');
},
});
});
}
// Extract Data from Page (Placeholder Function)
function extractDataFromPage(htmlContent, url) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlContent, 'text/html');
const title = doc.querySelector('title') ? doc.querySelector('title').innerText : '제목 없음';
const description = doc.querySelector('meta[name="description"]') ? doc.querySelector('meta[name="description"]').getAttribute('content') : '설명 없음';
return [{
name: title,
address: url,
description: description,
html: htmlContent,
}];
}
// Update Data Table
function updateDataTable() {
$('#crawler-data-table').find('tr:gt(0)').remove(); // Remove existing rows
crawledData.forEach(data => {
const row = $('<tr>').appendTo(dataTable);
$('<td>', { text: data.name, css: { border: '1px solid #ccc', padding: '5px' } }).appendTo(row);
$('<td>', { text: data.address, css: { border: '1px solid #ccc', padding: '5px' } }).appendTo(row);
$('<td>', { text: data.description, css: { border: '1px solid #ccc', padding: '5px' } }).appendTo(row);
$('<td>', {
text: '보기',
css: { border: '1px solid #ccc', padding: '5px', color: 'blue', cursor: 'pointer', 'text-decoration': 'underline' },
title: 'HTML 내용 보기'
}).on('click', () => showHTMLModal(data.html)).appendTo(row);
});
}
// Show HTML Modal
function showHTMLModal(htmlContent) {
const modal = $('<div>', {
css: {
position: 'fixed',
top: '0',
left: '0',
width: '100%',
height: '100%',
'background-color': 'rgba(0,0,0,0.5)',
'z-index': 10001,
display: 'flex',
'align-items': 'center',
'justify-content': 'center',
}
}).appendTo('body');
const modalContent = $('<div>', {
css: {
width: '80%',
height: '80%',
background: '#fff',
padding: '20px',
'overflow-y': 'auto',
'border-radius': '5px',
position: 'relative',
}
}).appendTo(modal);
$('<button>', {
text: '닫기',
css: {
position: 'absolute',
top: '10px',
right: '10px',
padding: '5px 10px',
cursor: 'pointer',
},
title: '모달 창을 닫습니다.'
}).on('click', () => modal.remove()).appendTo(modalContent);
$('<pre>', {
text: htmlContent,
css: { 'white-space': 'pre-wrap', 'word-wrap': 'break-word' }
}).appendTo(modalContent);
}
// Log Function
function log(message) {
const timestamp = new Date().toLocaleTimeString();
$('#crawler-log').append(`<div>[${timestamp}] ${message}</div>`);
$('#crawler-log').scrollTop($('#crawler-log')[0].scrollHeight);
}
// Update Progress
function updateProgress(percent) {
percent = Math.min(percent, 100);
$('#crawler-progress-bar').css('width', `${percent}%`);
$('#crawler-progress-percent').text(`${percent.toFixed(2)}%`);
}
// Delay Function
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Download CSV
function downloadCSV() {
if (crawledData.length === 0) {
log('다운로드할 데이터가 없습니다.');
return;
}
const csvContent = "data:text/csv;charset=utf-8,"
+ ["사이트 이름,주소,설명"].concat(
crawledData.map(e => `"${e.name}","${e.address}","${e.description}"`)
).join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "crawler_data.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
log('CSV 파일이 다운로드되었습니다.');
}
// Download JSON
function downloadJSON() {
if (crawledData.length === 0) {
log('다운로드할 데이터가 없습니다.');
return;
}
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(crawledData, null, 2));
const link = document.createElement("a");
link.setAttribute("href", dataStr);
link.setAttribute("download", "crawler_data.json");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
log('JSON 파일이 다운로드되었습니다.');
}
///////////////////////
// Data Table Search
///////////////////////
$('#crawler-data-table').before(searchInput);
searchInput.on('input', function() {
const keyword = $(this).val().toLowerCase();
$('#crawler-data-table tr').each(function(index) {
if (index === 0) return; // Skip header
const rowText = $(this).text().toLowerCase();
$(this).toggle(rowText.includes(keyword));
});
});
///////////////////////
// Initialize
///////////////////////
switchTab(1); // Default to Log Tab
///////////////////////
// Additional Features
///////////////////////
// CSS Enhancements
$('<style>').text(`
#crawler-data-table th, #crawler-data-table td {
border: 1px solid #ccc;
padding: 5px;
text-align: left;
}
#crawler-data-table th {
background-color: #eee;
}
#crawler-data-table tr:nth-child(even) {
background-color: #f9f9f9;
}
#crawler-data-table tr:hover {
background-color: #f1f1f1;
}
#crawler-container::-webkit-scrollbar {
width: 8px;
}
#crawler-container::-webkit-scrollbar-thumb {
background-color: rgba(0,0,0,0.2);
border-radius: 4px;
}
`).appendTo('head');
})();