javascript Copy code
// ==UserScript==
// @name Advanced Web Crawler
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Automated web crawler with advanced features
// @author Your Name
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_download
// @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
// ==/UserScript==
(function() {
'use strict';
// Initialize variables
let isCrawling = false;
let currentPage = 1;
let totalPages = 1;
let collectedData = [];
let visitedUrls = new Set(GM_getValue("visitedUrls", []).split(','));
let blacklist = new Set(GM_getValue("blacklist", []).split(','));
let whitelist = new Set(GM_getValue("whitelist", []).split(','));
let delay = 3000; // Default delay in ms
// Create UI
const createUI = () => {
// Main container
const container = $('<div>', { id: 'crawlerContainer', style: `
position: fixed; top: 10px; right: 10px; width: 800px; height: 600px;
background: white; border: 2px solid #000; z-index: 10000; font-family: Arial, sans-serif;
display: flex; flex-direction: column;
`}).appendTo('body');
// Tab headers
const tabs = $('<div>', { class: 'tabs', style: `
display: flex; background: #f1f1f1; cursor: pointer;
`}).appendTo(container);
const tabNames = ['📜 로그', '📊 데이터', '⚙️ 설정'];
tabNames.forEach((name, index) => {
$('<div>', { text: name, class: 'tab', 'data-tab': index, style: `
padding: 10px; flex: 1; text-align: center;
border-right: ${index < tabNames.length -1 ? '1px solid #ccc' : 'none'};
`}).hover(
function() { $(this).css('background', '#ddd'); },
function() { if(!$(this).hasClass('active')) $(this).css('background', '#f1f1f1'); }
).click(function() {
$('.tab').removeClass('active').css('background', '#f1f1f1');
$(this).addClass('active').css('background', '#ccc');
$('.tabContent').hide();
$(`#tabContent${$(this).data('tab')}`).show();
}).appendTo(tabs);
});
// Activate first tab
$('.tab').first().addClass('active').css('background', '#ccc');
// Tab contents
// Logs Tab
const logsTab = $('<div>', { id: 'tabContent0', class: 'tabContent', style: 'flex: 1; padding: 10px; overflow-y: auto;' }).show().appendTo(container);
$('<textarea>', { id: 'logArea', style: 'width: 100%; height: 100%; resize: none;' }).appendTo(logsTab);
// Data Tab
const dataTab = $('<div>', { id: 'tabContent1', class: 'tabContent', style: 'flex: 1; padding: 10px; display: none; overflow-y: auto;' }).appendTo(container);
const searchInput = $('<input>', { type: 'text', id: 'searchInput', placeholder: '검색...', style: 'width: 100%; padding: 5px; margin-bottom: 10px;' }).appendTo(dataTab);
const table = $('<table>', { id: 'dataTable', style: 'width: 100%; border-collapse: collapse;' }).appendTo(dataTab);
const thead = $('<thead>').appendTo(table);
$('<tr>').append(
$('<th>', { text: '사이트 이름', style: 'border: 1px solid #000; padding: 5px;' }),
$('<th>', { text: '주소', style: 'border: 1px solid #000; padding: 5px;' }),
$('<th>', { text: '설명', style: 'border: 1px solid #000; padding: 5px;' }),
$('<th>', { text: '분류', style: 'border: 1px solid #000; padding: 5px;' })
).appendTo(thead);
$('<tbody>', { id: 'dataBody' }).appendTo(table);
// Settings Tab
const settingsTab = $('<div>', { id: 'tabContent2', class: 'tabContent', style: 'flex: 1; padding: 10px; display: none; overflow-y: auto;' }).appendTo(container);
// Delay Setting
$('<label>', { text: '크롤링 딜레이 (ms): ', for: 'delayInput' }).appendTo(settingsTab);
$('<input>', { type: 'number', id: 'delayInput', value: delay, style: 'width: 100%; padding: 5px; margin-bottom: 10px;' }).appendTo(settingsTab);
// Blacklist
$('<label>', { text: '블랙리스트 도메인 (콤마로 구분): ', for: 'blacklistInput' }).appendTo(settingsTab);
$('<textarea>', { id: 'blacklistInput', style: 'width: 100%; height: 60px; padding: 5px;' }).val(Array.from(blacklist).join(',')).appendTo(settingsTab);
// Whitelist
$('<label>', { text: '화이트리스트 도메인 (콤마로 구분): ', for: 'whitelistInput' }).appendTo(settingsTab);
$('<textarea>', { id: 'whitelistInput', style: 'width: 100%; height: 60px; padding: 5px;' }).val(Array.from(whitelist).join(',')).appendTo(settingsTab);
// Save Settings Button
$('<button>', { text: '설정 저장', id: 'saveSettings', style: 'padding: 10px; width: 100%; cursor: pointer;' }).appendTo(settingsTab).click(saveSettings);
// Progress Bar
const progressBar = $('<div>', { style: `
width: 100%; background: #f3f3f3; border: 1px solid #ccc; height: 20px; margin-top: 10px;
`}).appendTo(container);
const progress = $('<div>', { id: 'progress', style: `
width: 0%; height: 100%; background: #4caf50;
`}).appendTo(progressBar);
// Controls
const controls = $('<div>', { style: 'display: flex; justify-content: space-between; margin-top: 10px;' }).appendTo(container);
$('<button>', { text: '크롤링 시작', id: 'startCrawl', style: 'padding: 10px; cursor: pointer;', title: 'Ctrl+P' }).appendTo(controls).click(startCrawling);
$('<button>', { text: '크롤링 중지', id: 'stopCrawl', style: 'padding: 10px; cursor: pointer;', title: 'Ctrl+Q' }).appendTo(controls).click(stopCrawling);
$('<button>', { text: 'CSV 다운로드', id: 'downloadCSV', style: 'padding: 10px; cursor: pointer;', title: 'Ctrl+D' }).appendTo(controls).click(downloadCSV);
$('<button>', { text: 'JSON 다운로드', id: 'downloadJSON', style: 'padding: 10px; cursor: pointer;', title: 'Ctrl+J' }).appendTo(controls).click(downloadJSON);
};
// Save Settings Function
const saveSettings = () => {
delay = parseInt($('#delayInput').val()) || 3000;
blacklist = new Set($('#blacklistInput').val().split(',').map(s => s.trim()).filter(s => s));
whitelist = new Set($('#whitelistInput').val().split(',').map(s => s.trim()).filter(s => s));
GM_setValue("blacklist", Array.from(blacklist).join(','));
GM_setValue("whitelist", Array.from(whitelist).join(','));
log('설정이 저장되었습니다.');
};
// Logging Function
const log = (message, type = 'info') => {
const timestamp = new Date().toLocaleString();
$('#logArea').append(`[${timestamp}] [${type.toUpperCase()}] ${message}\n`);
$('#logArea').scrollTop($('#logArea')[0].scrollHeight);
};
// Start Crawling Function
const startCrawling = async () => {
if (isCrawling) return;
isCrawling = true;
log('크롤링을 시작합니다.');
const query = prompt("검색어를 입력하세요:");
if (!query) {
log('검색어가 입력되지 않았습니다.', 'error');
isCrawling = false;
return;
}
currentPage = 1;
totalPages = await getTotalPages(query);
await crawlPage(query, currentPage);
log('크롤링이 완료되었습니다.');
isCrawling = false;
};
// Stop Crawling Function
const stopCrawling = () => {
if (!isCrawling) return;
isCrawling = false;
log('크롤링이 중지되었습니다.');
};
// Get Total Pages Function (Placeholder)
const getTotalPages = async (query) => {
// Implement logic to determine total pages based on the search query
// For example, parse the search results to find the total number of pages
return 5; // Placeholder value
};
// Crawl Page Function
const crawlPage = async (query, page) => {
if (!isCrawling || page > totalPages) return;
log(`페이지 ${page} 크롤링 중...`);
// Implement navigation to the search results page
// This is highly dependent on the website structure
// Example:
const searchUrl = `https://example.com/search?q=${encodeURIComponent(query)}&page=${page}`;
window.location.href = searchUrl;
// Wait for the page to load
await waitForPageLoad();
// Collect data from the current page
const results = collectDataFromPage();
for (let result of results) {
if (!visitedUrls.has(result.url) && isAllowed(result.url)) {
collectedData.push(result);
visitedUrls.add(result.url);
GM_setValue("visitedUrls", Array.from(visitedUrls).join(','));
updateTable(result);
updateProgress();
log(`수집된 데이터: ${result.name}`);
}
}
// Delay before next page
await sleep(delay);
// Proceed to next page
await crawlPage(query, page + 1);
};
// Check if URL is allowed based on whitelist and blacklist
const isAllowed = (url) => {
const domain = (new URL(url)).hostname;
if (whitelist.size > 0 && !whitelist.has(domain)) return false;
if (blacklist.has(domain)) return false;
return true;
};
// Collect Data from Page Function (Placeholder)
const collectDataFromPage = () => {
// Implement the logic to scrape the necessary data from the page
// This will vary based on the website's structure
// Example:
let data = [];
$('.search-result').each(function() {
const name = $(this).find('.site-name').text().trim();
const url = $(this).find('.site-link').attr('href');
const description = $(this).find('.site-description').text().trim();
data.push({ name, url, description, category: 'Uncategorized' });
});
return data;
};
// Wait for Page Load Function
const waitForPageLoad = () => {
return new Promise((resolve) => {
const checkReady = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(checkReady);
resolve();
}
}, 1000);
});
};
// Sleep Function
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Update Table Function
const updateTable = (data) => {
const row = $('<tr>').append(
$('<td>', { text: data.name, style: 'border: 1px solid #000; padding: 5px;' }),
$('<td>', {
text: data.url,
style: 'border: 1px solid #000; padding: 5px; color: blue; text-decoration: underline; cursor: pointer;',
click: () => window.open(data.url, '_blank')
}),
$('<td>', { text: data.description, style: 'border: 1px solid #000; padding: 5px;',
title: 'HTML 내용보기',
click: () => showModal(data)
}),
$('<td>', { text: data.category, style: 'border: 1px solid #000; padding: 5px;' })
).appendTo('#dataBody');
};
// Show Modal Function
const showModal = (data) => {
const modal = $('<div>', { style: `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center;
z-index: 10001;
`}).appendTo('body');
const content = $('<div>', { style: `
background: white; padding: 20px; width: 80%; height: 80%; overflow-y: auto; position: relative;
`}).appendTo(modal);
$('<h2>', { text: data.name }).appendTo(content);
$('<pre>', { text: data.description, style: 'white-space: pre-wrap;' }).appendTo(content);
$('<button>', { text: '닫기', style: `
position: absolute; top: 10px; right: 10px; padding: 5px; cursor: pointer;
` }).appendTo(content).click(() => modal.remove());
};
// Update Progress Function
const updateProgress = () => {
const progressPercent = (collectedData.length / 100) * 100; // Example calculation
$('#progress').css('width', `${progressPercent}%`);
};
// Download CSV Function
const downloadCSV = () => {
const worksheet = XLSX.utils.json_to_sheet(collectedData);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Data");
XLSX.writeFile(workbook, "data.csv");
log('CSV 파일이 다운로드되었습니다.');
};
// Download JSON Function
const downloadJSON = () => {
const blob = new Blob([JSON.stringify(collectedData, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = $('<a>', { href: url, download: 'data.json' }).appendTo('body');
a[0].click();
a.remove();
URL.revokeObjectURL(url);
log('JSON 파일이 다운로드되었습니다.');
};
// Keyboard Shortcuts
const setupShortcuts = () => {
$(document).keydown(function(e) {
if (e.ctrlKey && e.key === 'p') { // Ctrl+P
e.preventDefault();
startCrawling();
}
if (e.ctrlKey && e.key === 'q') { // Ctrl+Q
e.preventDefault();
stopCrawling();
}
if (e.ctrlKey && e.key === 'd') { // Ctrl+D
e.preventDefault();
downloadCSV();
}
if (e.ctrlKey && e.key === 'j') { // Ctrl+J
e.preventDefault();
downloadJSON();
}
if (e.ctrlKey && e.key === '1') { // Ctrl+1
e.preventDefault();
$('.tab').removeClass('active').css('background', '#f1f1f1');
$('.tab[data-tab="0"]').addClass('active').css('background', '#ccc');
$('.tabContent').hide();
$('#tabContent0').show();
}
if (e.ctrlKey && e.key === '2') { // Ctrl+2
e.preventDefault();
$('.tab').removeClass('active').css('background', '#f1f1f1');
$('.tab[data-tab="1"]').addClass('active').css('background', '#ccc');
$('.tabContent').hide();
$('#tabContent1').show();
}
if (e.ctrlKey && e.key === '3') { // Ctrl+3
e.preventDefault();
$('.tab').removeClass('active').css('background', '#f1f1f1');
$('.tab[data-tab="2"]').addClass('active').css('background', '#ccc');
$('.tabContent').hide();
$('#tabContent2').show();
}
});
};
// Filter Table Function
const setupSearch = () => {
$('#searchInput').on('input', function() {
const keyword = $(this).val().toLowerCase();
$('#dataBody tr').filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(keyword) > -1)
});
});
};
// Initialize
const init = () => {
createUI();
setupShortcuts();
setupSearch();
};
// Run the script
$(document).ready(init);
})();