당신의 웹 크롤러 스크립트는 이미 매우 포괄적이고 다양한 기능을 포함하고 있습니다. 그러나 다음과 같은 몇 가지 중요한 개선 사항을 통해 성능, 안정성 및 사용자 경험을 더욱 향상시킬 수 있습니다.
아래는 위의 개선 사항을 반영한 개선된 Userscript의 예시입니다. 이 스크립트는 모듈화, 향상된 에러 핸들링, UI 개선, 성능 최적화 등을 포함하고 있습니다.
javascript
// ==UserScript==
// @name 종합 웹 크롤러 7.2
// @namespace http://tampermonkey.net/
// @version 7.2
// @description 고급 기능을 갖춘 웹 크롤러로 검색 결과를 실시간으로 수집하고 표시 (개선됨)
// @author YourName
// @match *://www.google.com/search*
// @match *://www.bing.com/search*
// @match *://search.daum.net/search*
// @match *://search.naver.com/search*
// @match *://search.yahoo.com/search*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_notification
// @connect *
// @require https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js
// @require https://cdn.jsdelivr.net/npm/chart.js
// @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css
// @require https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js
// ==/UserScript==
(function() {
'use strict';
// =========================
// Utility Functions
// =========================
const Utils = {
escapeHTML: (str) => {
if (!str) return '';
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
},
escapeCSV: (str) => {
if (!str) return '';
return str.replace(/"/g, '""');
},
extractDomain: (url) => {
try {
const urlObj = new URL(url);
return urlObj.hostname.replace('www.', '');
} catch (e) {
return null;
}
},
formatTime: (seconds) => {
const hrs = String(Math.floor(seconds / 3600)).padStart(2, '0');
const mins = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
const secs = String(seconds % 60).padStart(2, '0');
return `${hrs}:${mins}:${secs}`;
},
getRandomUserAgent: () => {
const userAgents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
'Mozilla/5.0 (X11; Linux x86_64)',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
'Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X)',
'Mozilla/5.0 (Android 10; Mobile; rv:81.0) Gecko/81.0 Firefox/81.0',
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
];
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
};
// =========================
// Logger Module
// =========================
const Logger = {
logContainer: null,
logMessages: [],
init: function(container) {
this.logContainer = container.querySelector('#log');
this.loadLogs();
},
log: function(message, type = 'info') {
const time = new Date().toLocaleTimeString();
let coloredMessage = message;
switch(type) {
case 'warning':
coloredMessage = `<span style="color: orange;">⚠️ ${message}</span>`;
break;
case 'error':
coloredMessage = `<span style="color: red;">❌ ${message}</span>`;
break;
case 'success':
coloredMessage = `<span style="color: green;">✅ ${message}</span>`;
break;
default:
coloredMessage = `ℹ️ ${message}`;
}
const entry = `[${time}] ${coloredMessage}`;
this.logMessages.push(entry);
this.logContainer.innerHTML += `${entry}<br>`;
this.logContainer.scrollTop = this.logContainer.scrollHeight;
GM_setValue('crawlerLogs', JSON.stringify(this.logMessages));
},
loadLogs: function() {
const storedLogs = GM_getValue('crawlerLogs', []);
if (storedLogs.length > 0) {
this.logMessages = JSON.parse(storedLogs);
this.logContainer.innerHTML = `<strong>로그:</strong><br>` + this.logMessages.join('<br>');
this.logContainer.scrollTop = this.logContainer.scrollHeight;
}
},
exportLogs: function() {
if (this.logMessages.length === 0) {
alert('내보낼 로그가 없습니다.');
return;
}
const format = prompt('내보낼 로그 형식을 선택하세요 (txt, csv, json):', 'txt');
if (!format) return;
let blob, filename;
if (format.toLowerCase() === 'txt') {
blob = new Blob([this.logMessages.join('\n')], { type: 'text/plain;charset=utf-8;' });
filename = '크롤링_로그.txt';
} else if (format.toLowerCase() === 'csv') {
const csv = ['시간,메시지'].concat(this.logMessages.map(entry => entry.replace(/<[^>]+>/g, ''))).join('\n');
blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
filename = '크롤링_로그.csv';
} else if (format.toLowerCase() === 'json') {
const json = JSON.stringify(this.logMessages, null, 2);
blob = new Blob([json], { type: 'application/json;charset=utf-8;' });
filename = '크롤링_로그.json';
} else {
alert('지원하지 않는 형식입니다.');
return;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
this.log(`💾 로그를 "${filename}" 파일로 내보냈습니다.`, 'success');
GM_notification({
text: `로그를 "${filename}" 파일로 내보냈습니다.`,
title: '웹 크롤러 7.2',
timeout: 3000
});
}
};
// =========================
// UI Module
// =========================
const UI = {
container: null,
initialize: function() {
// CSS 스타일 추가 및 UI 구성
GM_addStyle(`
/* 기본 컨테이너 스타일 */
#crawler-container {
position: fixed;
top: 10px;
right: 10px;
background-color: #ffffff;
border: 2px solid #4CAF50;
padding: 20px;
z-index: 10000;
width: 95%;
max-width: 960px;
max-height: 90vh;
overflow: hidden;
box-shadow: 0 4px 30px rgba(0,0,0,0.3);
border-radius: 10px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 14px;
resize: both;
transition: all 0.3s ease;
}
/* 다크 모드 */
#crawler-container.dark-mode {
background-color: #2e2e2e;
color: #ffffff;
border-color: #555555;
}
#crawler-container.dark-mode input,
#crawler-container.dark-mode select,
#crawler-container.dark-mode textarea {
background-color: #444444;
color: #ffffff;
border-color: #777777;
}
/* 헤더 스타일 */
#crawler-container header {
cursor: move;
background-color: #4CAF50;
color: white;
padding: 10px;
border-radius: 8px 8px 0 0;
text-align: center;
font-size: 20px;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
}
/* 닫기 버튼 스타일 */
#crawler-container header .close-btn {
cursor: pointer;
font-size: 24px;
color: #ff4d4d;
}
/* 테마 전환 버튼 */
#crawler-container header .theme-toggle {
cursor: pointer;
font-size: 18px;
color: #ffffff;
margin-left: 10px;
}
/* 탭 스타일 */
#crawler-container .tablinks {
background-color: inherit;
border: none;
outline: none;
cursor: pointer;
padding: 10px 20px;
transition: 0.3s;
font-size: 16px;
}
#crawler-container .tablinks.active {
background-color: #ddd;
border-radius: 5px 5px 0 0;
}
/* 탭 컨텐츠 스타일 */
#crawler-container .tabcontent {
display: none;
padding: 10px 0;
overflow: auto;
}
#crawler-container .tabcontent.active {
display: block;
}
/* 버튼 스타일 */
#crawler-container button {
padding: 8px 12px;
margin: 5px 3px;
border: none;
border-radius: 4px;
background-color: #4CAF50;
color: white;
cursor: pointer;
transition: background-color 0.3s;
font-size: 14px;
}
#crawler-container button:hover {
background-color: #45a049;
}
/* 인풋 및 셀렉트 스타일 */
#crawler-container input[type="text"],
#crawler-container textarea,
#crawler-container input[type="number"],
#crawler-container select {
width: calc(100% - 16px);
padding: 8px;
margin: 5px 0 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
background-color: #f9f9f9;
color: #000000;
}
#crawler-container.dark-mode input[type="text"],
#crawler-container.dark-mode textarea,
#crawler-container.dark-mode input[type="number"],
#crawler-container.dark-mode select {
background-color: #555555;
color: #ffffff;
border-color: #777777;
}
/* 테이블 스타일 */
#crawler-container table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
#crawler-container th, #crawler-container td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
vertical-align: top;
}
#crawler-container th {
background-color: #4CAF50;
color: white;
}
#crawler-container.dark-mode th {
background-color: #333333;
color: #ffffff;
}
/* 로그 창 스타일 */
#crawler-container .log {
max-height: 250px;
overflow-y: auto;
background-color: #eef;
padding: 10px;
margin-top: 15px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 12px;
white-space: pre-wrap;
}
#crawler-container.dark-mode .log {
background-color: #444444;
color: #ffffff;
border-color: #666666;
}
/* 컨트롤 및 옵션 스타일 */
#crawler-container .controls,
#crawler-container .options,
#crawler-container .advanced-options,
#crawler-container .notification-area {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
#crawler-container .options label,
#crawler-container .advanced-options label {
margin-right: 15px;
display: flex;
align-items: center;
}
#crawler-container .options input[type="checkbox"],
#crawler-container .advanced-options input[type="checkbox"] {
margin-right: 5px;
}
#crawler-container .filters,
#crawler-container .exclude-domains {
margin-top: 10px;
width: 100%;
}
#crawler-container .filters label,
#crawler-container .exclude-domains label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
#crawler-container progress {
width: 80%;
height: 20px;
margin-right: 10px;
}
#crawler-container .status {
margin-top: 10px;
font-weight: bold;
}
/* 버튼 별 특수 스타일 */
#crawler-container .export-btn {
background-color: #2196F3;
}
#crawler-container .export-btn:hover {
background-color: #0b7dda;
}
#crawler-container .pause-btn {
background-color: #FF9800;
}
#crawler-container .pause-btn:hover {
background-color: #e68a00;
}
/* 차트 컨테이너 스타일 */
#crawler-container .chart-container {
position: relative;
height: 250px;
width: 100%;
margin-top: 20px;
}
/* 모달 창 스타일 */
.crawler-modal {
display: none;
position: fixed;
z-index: 10001;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.crawler-modal-content {
background-color: #fefefe;
margin: 5% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 800px;
border-radius: 10px;
position: relative;
}
.crawler-modal-content pre {
white-space: pre-wrap;
word-wrap: break-word;
max-height: 70vh;
overflow-y: auto;
}
.crawler-modal-close {
color: #aaa;
position: absolute;
top: 10px;
right: 20px;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.crawler-modal-close:hover,
.crawler-modal-close:focus {
color: black;
text-decoration: none;
}
/* 다크 모드 모달 창 */
#crawler-container.dark-mode .crawler-modal-content {
background-color: #333333;
color: #ffffff;
border-color: #555555;
}
/* HTML 내용 강조 */
.hljs {
background: none;
}
`);
// UI HTML 생성
this.container = document.createElement('div');
this.container.id = 'crawler-container';
this.container.innerHTML = `
<header>
<div style="display: flex; align-items: center;">
<span class="title">🔥 웹 크롤러 7.2</span>
<span class="theme-toggle" title="테마 전환">🌓</span>
</div>
<span class="close-btn">×</span>
</header>
<div class="tablinks">
<button class="tablink active" data-tab="settings">설정</button>
<button class="tablink" data-tab="results-section">결과</button>
<button class="tablink" data-tab="logs">로그</button>
</div>
<div id="settings" class="tabcontent active">
<div class="notification-area">
<button id="startBtn">시작</button>
<button id="pauseBtn" class="pause-btn">일시정지</button>
<button id="stopBtn">중지</button>
<button id="resetBtn">초기화</button>
<button id="exportBtn" class="export-btn">결과 내보내기</button>
<button id="exportLogBtn" class="export-btn">로그 내보내기</button>
</div>
<div class="options">
<label><input type="checkbox" id="toggleHTML" checked> HTML 가져오기</label>
<label><input type="checkbox" id="toggleImages" checked> 이미지 가져오기</label>
<label><input type="checkbox" id="toggleAds" checked> 광고 제외</label>
</div>
<div class="filters">
<label for="filterInput">필터 단어 (정규식, 쉼표로 구분):</label>
<input type="text" id="filterInput" placeholder="예: 기부, 광고, /promo/i">
</div>
<div class="exclude-domains">
<label for="excludeDomainsInput">제외할 도메인 (쉼표로 구분):</label>
<input type="text" id="excludeDomainsInput" placeholder="예: facebook.com, youtube.com">
</div>
<div class="advanced-options">
<label for="duplicateThreshold">중복 허용 횟수:</label>
<input type="number" id="duplicateThreshold" value="2" min="1" style="width: 60px;">
</div>
<div class="controls">
<label for="retryAttempts">재시도 횟수:</label>
<input type="number" id="retryAttempts" value="3" min="1" style="width: 60px;">
<label for="retryInterval">재시도 간격 (ms):</label>
<input type="number" id="retryInterval" value="500" min="100" style="width: 80px;">
</div>
<div style="margin-top:10px;">
<label for="progressBar">진행률:</label>
<progress id="progressBar" value="0" max="100"></progress>
<span id="progressText">0%</span>
</div>
<div class="status">
현재 페이지: <span id="currentPage">0</span> /
총 페이지: <span id="totalPages">0</span>
<br>
방문된 사이트: <span id="visitedCount">0</span>
<br>
경과 시간: <span id="elapsedTime">00:00:00</span>
<br>
예상 남은 시간: <span id="remainingTime">00:00:00</span>
</div>
<div class="chart-container">
<canvas id="crawlChart"></canvas>
</div>
</div>
<div id="results-section" class="tabcontent">
<div id="results" style="margin-top:10px; max-height: 400px; overflow: auto;">
<table id="resultsTable">
<thead>
<tr>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>이미지</th>
<th>HTML 링크</th>
<th>WHOIS 정보</th>
<th>페이지 로딩 시간 (ms)</th>
<th>HTML 보기</th>
</tr>
</thead>
<tbody id="resultsBody">
</tbody>
</table>
</div>
<div class="keyword-analysis" style="margin-top:20px;">
<h3>키워드 빈도 분석</h3>
<canvas id="keywordChart"></canvas>
</div>
</div>
<div id="logs" class="tabcontent">
<div class="log" id="log">
<strong>로그:</strong>
</div>
</div>
<!-- HTML 보기 모달 창 추가 -->
<div id="htmlModal" class="crawler-modal">
<div class="crawler-modal-content">
<span class="crawler-modal-close">×</span>
<h2>사이트 HTML</h2>
<pre><code id="htmlContent" class="html"></code></pre>
</div>
</div>
`;
document.body.appendChild(this.container);
// 드래그 가능하게 설정
this.makeDraggable(this.container);
// 탭 전환 기능 추가
this.initializeTabs();
// 다크 모드 토글 기능
this.initializeThemeToggle();
// 모달 창 기능
this.initializeModal();
// 버튼 이벤트 리스너 등록
this.initializeEventListeners();
},
makeDraggable: function(elmnt) {
const header = elmnt.querySelector('header');
const closeBtn = elmnt.querySelector('.close-btn');
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
header.onmousedown = dragMouseDown;
closeBtn.onclick = () => {
elmnt.style.display = 'none';
};
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
},
initializeTabs: function() {
const tabbuttons = this.container.querySelectorAll('.tablinks button');
const tabs = this.container.querySelectorAll('.tabcontent');
tabbuttons.forEach(tab => {
tab.addEventListener('click', () => {
const tabName = tab.getAttribute('data-tab');
tabs.forEach(tc => tc.classList.remove('active'));
tabbuttons.forEach(t => t.classList.remove('active'));
this.container.querySelector(`#${tabName}`).classList.add('active');
tab.classList.add('active');
});
});
},
initializeThemeToggle: function() {
const themeToggleBtn = this.container.querySelector('.theme-toggle');
themeToggleBtn.addEventListener('click', () => {
this.container.classList.toggle('dark-mode');
GM_setValue('darkMode', this.container.classList.contains('dark-mode'));
});
const savedTheme = GM_getValue('darkMode', false);
if (savedTheme) {
this.container.classList.add('dark-mode');
}
},
initializeModal: function() {
const modal = document.getElementById("htmlModal");
const modalClose = this.container.querySelector(".crawler-modal-close");
modalClose.onclick = function() {
modal.style.display = "none";
};
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
},
initializeEventListeners: function() {
// Initialize Logger
Logger.init(this.container);
// Export Log Button
const exportLogBtn = this.container.querySelector('#exportLogBtn');
exportLogBtn.addEventListener('click', Logger.exportLogs.bind(Logger));
// Other buttons will be initialized in the Controller module
}
};
// =========================
// Controller Module
// =========================
const Controller = {
state: {
isRunning: false,
isPaused: false,
currentPage: 1,
totalPages: 0,
results: [],
searchQuery: '',
searchEngine: '',
visitedLinks: new Map(),
filterPatterns: [],
excludeDomains: [],
duplicateThreshold: 2,
retryAttempts: 3,
retryInterval: 500,
startTime: null,
elapsedInterval: null,
crawlChart: null,
keywordChart: null,
keywordFrequency: {}
},
elements: {},
init: function() {
this.cacheElements();
this.initializeCharts();
this.restoreState();
this.attachEventListeners();
},
cacheElements: function() {
this.elements = {
startBtn: UI.container.querySelector('#startBtn'),
pauseBtn: UI.container.querySelector('#pauseBtn'),
stopBtn: UI.container.querySelector('#stopBtn'),
resetBtn: UI.container.querySelector('#resetBtn'),
exportBtn: UI.container.querySelector('#exportBtn'),
progressBar: UI.container.querySelector('#progressBar'),
progressText: UI.container.querySelector('#progressText'),
resultsBody: UI.container.querySelector('#resultsBody'),
currentPageElem: UI.container.querySelector('#currentPage'),
totalPagesElem: UI.container.querySelector('#totalPages'),
toggleHTML: UI.container.querySelector('#toggleHTML'),
toggleImages: UI.container.querySelector('#toggleImages'),
toggleAds: UI.container.querySelector('#toggleAds'),
filterInput: UI.container.querySelector('#filterInput'),
excludeDomainsInput: UI.container.querySelector('#excludeDomainsInput'),
duplicateThresholdInput: UI.container.querySelector('#duplicateThreshold'),
retryAttemptsInput: UI.container.querySelector('#retryAttempts'),
retryIntervalInput: UI.container.querySelector('#retryInterval'),
visitedCountElem: UI.container.querySelector('#visitedCount'),
elapsedTimeElem: UI.container.querySelector('#elapsedTime'),
remainingTimeElem: UI.container.querySelector('#remainingTime'),
crawlChartCtx: UI.container.querySelector('#crawlChart').getContext('2d'),
keywordChartCtx: UI.container.querySelector('#keywordChart').getContext('2d'),
htmlModal: UI.container.querySelector('#htmlModal'),
htmlContent: UI.container.querySelector('#htmlContent'),
exportLogBtn: UI.container.querySelector('#exportLogBtn')
};
},
initializeCharts: function() {
this.state.crawlChart = new Chart(this.elements.crawlChartCtx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '방문 횟수',
data: [],
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '방문 횟수'
}
},
x: {
title: {
display: true,
text: '도메인'
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
enabled: true
}
}
}
});
this.state.keywordChart = new Chart(this.elements.keywordChartCtx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '키워드 빈도',
data: [],
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '빈도'
}
},
x: {
title: {
display: true,
text: '키워드'
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
enabled: true
}
}
}
});
// 로드된 데이터가 있는 경우 차트 업데이트
const storedCrawlData = GM_getValue('crawlerData', null);
if (storedCrawlData) {
const parsedCrawlData = JSON.parse(storedCrawlData);
this.state.crawlChart.data = parsedCrawlData;
this.state.crawlChart.update();
}
const storedKeywordData = GM_getValue('keywordData', null);
if (storedKeywordData) {
const parsedKeywordData = JSON.parse(storedKeywordData);
this.state.keywordChart.data = parsedKeywordData;
this.state.keywordChart.update();
}
},
attachEventListeners: function() {
this.elements.startBtn.addEventListener('click', this.startCrawling.bind(this));
this.elements.pauseBtn.addEventListener('click', this.togglePause.bind(this));
this.elements.stopBtn.addEventListener('click', this.stopCrawling.bind(this));
this.elements.resetBtn.addEventListener('click', this.resetCrawling.bind(this));
this.elements.exportBtn.addEventListener('click', this.exportResults.bind(this));
this.elements.exportLogBtn.addEventListener('click', Logger.exportLogs.bind(Logger));
this.elements.filterInput.addEventListener('input', this.updateFilterPatterns.bind(this));
this.elements.excludeDomainsInput.addEventListener('input', this.updateExcludeDomains.bind(this));
this.elements.duplicateThresholdInput.addEventListener('change', this.updateDuplicateThreshold.bind(this));
this.elements.retryAttemptsInput.addEventListener('change', this.updateRetryAttempts.bind(this));
this.elements.retryIntervalInput.addEventListener('change', this.updateRetryInterval.bind(this));
// 페이지 새로 고침 시 크롤링 초기화
window.addEventListener('beforeunload', () => {
this.resetCrawling();
});
},
getSearchQueryAndEngine: function() {
const url = window.location.href;
if (url.includes('google.com/search')) {
const params = new URLSearchParams(window.location.search);
this.state.searchQuery = params.get('q') || '';
this.state.searchEngine = 'google';
} else if (url.includes('bing.com/search')) {
const params = new URLSearchParams(window.location.search);
this.state.searchQuery = params.get('q') || '';
this.state.searchEngine = 'bing';
} else if (url.includes('daum.net/search')) {
const params = new URLSearchParams(window.location.search);
this.state.searchQuery = params.get('q') || '';
this.state.searchEngine = 'daum';
} else if (url.includes('search.naver.com/search')) {
const params = new URLSearchParams(window.location.search);
this.state.searchQuery = params.get('query') || '';
this.state.searchEngine = 'naver';
} else if (url.includes('search.yahoo.com/search')) {
const params = new URLSearchParams(window.location.search);
this.state.searchQuery = params.get('p') || '';
this.state.searchEngine = 'yahoo';
} else {
this.state.searchQuery = '';
this.state.searchEngine = '';
}
Logger.log(`🔍 검색 엔진: ${this.state.searchEngine}, 검색어: "${this.state.searchQuery}"`);
},
startCrawling: async function() {
if (this.state.isRunning) {
alert('이미 크롤링이 진행 중입니다.');
return;
}
this.getSearchQueryAndEngine();
if (!this.state.searchQuery) {
alert('현재 페이지에서 검색어를 찾을 수 없습니다.');
Logger.log('⚠️ 검색어 미입력 또는 인식 실패.', 'warning');
return;
}
this.state.isRunning = true;
this.state.isPaused = false;
this.state.currentPage = 1;
this.state.totalPages = 0;
this.state.results = [];
this.state.keywordFrequency = {};
this.state.visitedLinks.clear();
this.elements.resultsBody.innerHTML = '';
this.elements.visitedCountElem.innerText = '0';
this.elements.elapsedTimeElem.innerText = '00:00:00';
this.elements.remainingTimeElem.innerText = '00:00:00';
Logger.log('✅ 크롤링을 시작합니다.', 'success');
this.updateDuplicateThreshold();
this.updateRetryAttempts();
this.updateRetryInterval();
await this.crawlPage();
this.state.startTime = Date.now();
this.state.elapsedInterval = setInterval(this.updateElapsedTime.bind(this), 1000);
},
togglePause: function() {
if (!this.state.isRunning) {
alert('일시정지/재개할 크롤링이 없습니다.');
return;
}
this.state.isPaused = !this.state.isPaused;
if (this.state.isPaused) {
Logger.log('⏸️ 크롤링을 일시정지하였습니다.', 'warning');
this.elements.pauseBtn.innerText = '재개';
} else {
Logger.log('▶️ 크롤링을 재개하였습니다.', 'success');
this.elements.pauseBtn.innerText = '일시정지';
this.crawlPage();
}
},
stopCrawling: function() {
if (!this.state.isRunning) {
alert('중지할 크롤링이 없습니다.');
return;
}
this.state.isRunning = false;
this.state.isPaused = false;
this.elements.pauseBtn.innerText = '일시정지';
clearInterval(this.state.elapsedInterval);
this.updateProgress();
Logger.log('🚫 크롤링을 중지하였습니다.', 'error');
GM_notification({
text: '크롤링이 중지되었습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
},
resetCrawling: function() {
this.state.isRunning = false;
this.state.isPaused = false;
this.state.currentPage = 1;
this.state.totalPages = 0;
this.state.results = [];
this.state.keywordFrequency = {};
this.state.visitedLinks.clear();
this.elements.resultsBody.innerHTML = '';
this.elements.progressBar.value = 0;
this.elements.progressText.innerText = '0%';
this.elements.currentPageElem.innerText = '0';
this.elements.totalPagesElem.innerText = '0';
this.elements.visitedCountElem.innerText = '0';
this.elements.elapsedTimeElem.innerText = '00:00:00';
this.elements.remainingTimeElem.innerText = '00:00:00';
Logger.log('🔄 크롤링을 초기화하였습니다.', 'info');
clearInterval(this.state.elapsedInterval);
// 차트 초기화
this.state.crawlChart.data.labels = [];
this.state.crawlChart.data.datasets[0].data = [];
this.state.crawlChart.update();
this.state.keywordChart.data.labels = [];
this.state.keywordChart.data.datasets[0].data = [];
this.state.keywordChart.update();
// 로그 초기화
Logger.logMessages = [];
Logger.logContainer.innerHTML = `<strong>로그:</strong><br>`;
GM_setValue('crawlerLogs', JSON.stringify(Logger.logMessages));
},
updateFilterPatterns: function() {
const input = this.elements.filterInput.value.trim();
this.state.filterPatterns = input ? input.split(',').map(word => {
word = word.trim();
if (word.startsWith('/') && word.endsWith('/')) {
try {
return new RegExp(word.slice(1, -1), 'i');
} catch (e) {
Logger.log(`⚠️ 유효하지 않은 정규식: ${word}`, 'warning');
return null;
}
} else {
return new RegExp(word, 'i');
}
}).filter(regex => regex !== null) : [];
Logger.log(`🛠 필터 패턴 업데이트: [${this.state.filterPatterns.map(r => r.toString()).join(', ')}]`);
},
updateExcludeDomains: function() {
const input = this.elements.excludeDomainsInput.value.trim();
this.state.excludeDomains = input ? input.split(',').map(domain => domain.trim().toLowerCase()) : [];
Logger.log(`🚫 제외 도메인 업데이트: [${this.state.excludeDomains.join(', ')}]`);
},
updateDuplicateThreshold: function() {
const value = parseInt(this.elements.duplicateThresholdInput.value);
this.state.duplicateThreshold = isNaN(value) || value < 1 ? 2 : value;
Logger.log(`🔄 중복 허용 횟수 설정: ${this.state.duplicateThreshold}`);
},
updateRetryAttempts: function() {
const value = parseInt(this.elements.retryAttemptsInput.value);
this.state.retryAttempts = isNaN(value) || value < 1 ? 3 : value;
Logger.log(`🔄 재시도 횟수 설정: ${this.state.retryAttempts}`);
},
updateRetryInterval: function() {
const value = parseInt(this.elements.retryIntervalInput.value);
this.state.retryInterval = isNaN(value) || value < 100 ? 500 : value;
Logger.log(`🔄 재시도 간격 설정: ${this.state.retryInterval}ms`);
},
crawlPage: async function() {
if (!this.state.isRunning || this.state.isPaused) return;
let url = this.constructURL(this.state.currentPage);
if (!url) {
alert('지원하지 않는 검색 엔진입니다.');
Logger.log('❌ 지원하지 않는 검색 엔진.', 'error');
this.stopCrawling();
return;
}
Logger.log(`📄 페이지 ${this.state.currentPage} 크롤링 중: ${url}`);
try {
const response = await this.fetchPage(url);
if (response.status !== 200) {
Logger.log(`❌ 페이지 ${this.state.currentPage} 로드 실패: 상태 ${response.status}`, 'error');
this.handleCrawlError(this.state.currentPage, this.state.retryAttempts);
return;
}
const doc = this.parseHTML(response.responseText);
const items = this.extractItems(doc);
Logger.log(`📊 페이지 ${this.state.currentPage}에서 ${items.length}개 항목 발견.`);
await this.processItems(items);
this.updateChart();
this.updateKeywordChart();
this.updateProgress();
this.state.currentPage++;
this.elements.currentPageElem.innerText = this.state.currentPage;
// 크롤링 계속 진행
setTimeout(this.crawlPage.bind(this), this.state.isPaused ? 0 : 0); // 속도 제한 추가 가능
} catch (error) {
Logger.log(`❌ 페이지 ${this.state.currentPage} 요청 중 오류 발생: ${error}`, 'error');
this.handleCrawlError(this.state.currentPage, this.state.retryAttempts);
}
},
constructURL: function(page) {
const query = encodeURIComponent(this.state.searchQuery);
switch(this.state.searchEngine) {
case 'google':
return `https://www.google.com/search?q=${query}&start=${(page-1)*10}`;
case 'bing':
return `https://www.bing.com/search?q=${query}&first=${(page-1)*10 +1}`;
case 'daum':
return `https://search.daum.net/search?q=${query}&page=${page}`;
case 'naver':
return `https://search.naver.com/search.naver?query=${query}&start=${(page-1)*10 +1}`;
case 'yahoo':
return `https://search.yahoo.com/search?p=${query}&b=${(page-1)*10 +1}`;
default:
return '';
}
},
fetchPage: function(url) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: url,
headers: {
"User-Agent": Utils.getRandomUserAgent(),
"Accept": "text/html"
},
onload: resolve,
onerror: reject
});
});
},
parseHTML: function(htmlText) {
const parser = new DOMParser();
return parser.parseFromString(htmlText, 'text/html');
},
extractItems: function(doc) {
switch(this.state.searchEngine) {
case 'google':
return Array.from(doc.querySelectorAll('div.g'));
case 'bing':
return Array.from(doc.querySelectorAll('li.b_algo'));
case 'daum':
return Array.from(doc.querySelectorAll('div.wrap_cont'));
case 'naver':
return Array.from(doc.querySelectorAll('div.basic1'));
case 'yahoo':
return Array.from(doc.querySelectorAll('div.compTitle'));
default:
return [];
}
},
processItems: async function(items) {
const itemPromises = items.map(async (item) => {
let { title, link, description, image, htmlLink, whoisInfo, pageLoadTime } = {
title: 'N/A',
link: 'N/A',
description: 'N/A',
image: 'N/A',
htmlLink: 'N/A',
whoisInfo: 'N/A',
pageLoadTime: 'N/A'
};
// 추출 로직 (검색 엔진별)
switch(this.state.searchEngine) {
case 'google':
title = item.querySelector('h3')?.innerText || 'N/A';
link = item.querySelector('a')?.href || 'N/A';
description = item.querySelector('.IsZvec')?.innerText || item.querySelector('.VwiC3b')?.innerText || 'N/A';
const imgG = item.querySelector('img');
if (imgG && imgG.src) {
image = `<img src="${imgG.src}" alt="이미지" style="max-width: 100px; max-height: 100px;">`;
}
break;
case 'bing':
const titleB = item.querySelector('h2 a');
if (titleB) {
title = titleB.innerText;
link = titleB.href;
}
description = item.querySelector('p')?.innerText || 'N/A';
const imgB = item.querySelector('img');
if (imgB && imgB.src) {
image = `<img src="${imgB.src}" alt="이미지" style="max-width: 100px; max-height: 100px;">`;
}
break;
case 'daum':
const titleD = item.querySelector('a.link_fax');
if (titleD) {
title = titleD.innerText.trim();
link = titleD.href;
}
description = item.querySelector('div.cont_inner')?.innerText.trim() || 'N/A';
const imgD = item.querySelector('img');
if (imgD && imgD.src) {
image = `<img src="${imgD.src}" alt="이미지" style="max-width: 100px; max-height: 100px;">`;
}
break;
case 'naver':
const titleN = item.querySelector('a.tit');
if (titleN) {
title = titleN.innerText;
link = titleN.href;
}
description = item.querySelector('div.desc')?.innerText || 'N/A';
const imgN = item.querySelector('img.thumb');
if (imgN && imgN.src) {
image = `<img src="${imgN.src}" alt="이미지" style="max-width: 100px; max-height: 100px;">`;
}
break;
case 'yahoo':
const titleY = item.querySelector('h3');
if (titleY) {
title = titleY.innerText;
}
link = item.querySelector('a')?.href || 'N/A';
description = item.querySelector('div.compText')?.innerText || 'N/A';
const imgY = item.querySelector('img');
if (imgY && imgY.src) {
image = `<img src="${imgY.src}" alt="이미지" style="max-width: 100px; max-height: 100px;">`;
}
break;
default:
break;
}
// 광고 제외
if (this.state.toggleAds && this.isAd(title, description)) {
Logger.log(`🚫 광고 항목 제외: "${title}"`, 'warning');
return;
}
// 필터 단어 적용
if (this.state.filterPatterns.length > 0 && this.isFiltered(title, description)) {
Logger.log(`❌ 필터 단어 포함 항목 제외: "${title}"`, 'warning');
return;
}
// 도메인 추출 및 제외 도메인 검사
const domain = Utils.extractDomain(link);
if (!domain) return;
if (this.state.excludeDomains.includes(domain.toLowerCase())) {
Logger.log(`🚫 제외 도메인 항목 제외: "${link}"`, 'warning');
return;
}
// 중복 검사
let visitCount = this.state.visitedLinks.get(domain) || 0;
if (visitCount >= this.state.duplicateThreshold) {
Logger.log(`🔄 중복 방문 제한: "${domain}"`, 'warning');
return;
}
this.state.visitedLinks.set(domain, visitCount + 1);
this.elements.visitedCountElem.innerText = this.state.visitedLinks.size.toString();
// 페이지 로딩 시간 측정
try {
const startLoad = performance.now();
await fetch(link, { mode: 'no-cors' });
const endLoad = performance.now();
pageLoadTime = Math.round(endLoad - startLoad);
} catch (err) {
pageLoadTime = '계산 불가';
}
// 키워드 빈도 분석
this.analyzeKeywords(`${title} ${description}`);
// WHOIS 정보 (예시로 링크 추가)
whoisInfo = `<a href="https://who.is/whois/${encodeURIComponent(domain)}" target="_blank">보기</a>`;
// 이미지 옵션
if (!this.state.toggleImages) {
image = '비활성화';
}
// HTML 보기 버튼
if (this.state.toggleHTML && link !== 'N/A') {
htmlLink = `<button class="view-html-btn" data-url="${encodeURIComponent(link)}">보기</button>`;
}
// 결과에 추가
this.state.results.push({ title, link, description, image, htmlLink, whoisInfo, pageLoadTime });
this.addResultRow({ title, link, description, image, htmlLink, whoisInfo, pageLoadTime });
});
await Promise.all(itemPromises);
},
isAd: function(title, description) {
const combinedText = `${title} ${description}`.toLowerCase();
return combinedText.includes('advertisement') || combinedText.includes('광고');
},
isFiltered: function(title, description) {
const combinedText = `${title} ${description}`.toLowerCase();
return this.state.filterPatterns.some(regex => regex.test(combinedText));
},
addResultRow: function(row) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${Utils.escapeHTML(row.title)}</td>
<td><a href="${Utils.escapeHTML(row.link)}" target="_blank">${Utils.escapeHTML(row.link)}</a></td>
<td>${Utils.escapeHTML(row.description)}</td>
<td>${row.image}</td>
<td>${row.htmlLink}</td>
<td>${row.whoisInfo}</td>
<td>${row.pageLoadTime}</td>
<td>${row.htmlLink !== 'N/A' ? row.htmlLink : 'N/A'}</td>
`;
this.elements.resultsBody.appendChild(tr);
this.addHTMLViewEventListeners();
},
addHTMLViewEventListeners: function() {
const buttons = UI.container.querySelectorAll('.view-html-btn');
buttons.forEach(button => {
button.addEventListener('click', async () => {
const url = decodeURIComponent(button.getAttribute('data-url'));
Logger.log(`📄 HTML을 불러오는 중: ${url}`);
try {
const response = await fetch(url);
const htmlText = await response.text();
this.elements.htmlContent.textContent = htmlText;
hljs.highlightElement(this.elements.htmlContent); // 구문 강조
UI.container.querySelector("#htmlModal").style.display = "block";
Logger.log(`✅ HTML 불러오기 완료: ${url}`, 'success');
} catch (err) {
Logger.log(`❌ HTML 불러오기 실패: ${url}`, 'error');
this.elements.htmlContent.textContent = 'HTML을 불러오는 데 실패했습니다.';
UI.container.querySelector("#htmlModal").style.display = "block";
}
});
});
},
analyzeKeywords: function(text) {
const words = text.toLowerCase().match(/\b\w+\b/g);
if (!words) return;
words.forEach(word => {
if (word.length < 2) return;
this.state.keywordFrequency[word] = (this.state.keywordFrequency[word] || 0) + 1;
});
},
updateChart: function() {
this.state.crawlChart.data.labels = Array.from(this.state.visitedLinks.keys());
this.state.crawlChart.data.datasets[0].data = Array.from(this.state.visitedLinks.values());
this.state.crawlChart.update();
GM_setValue('crawlerData', JSON.stringify(this.state.crawlChart.data));
},
updateKeywordChart: function() {
this.state.keywordChart.data.labels = Object.keys(this.state.keywordFrequency);
this.state.keywordChart.data.datasets[0].data = Object.values(this.state.keywordFrequency);
this.state.keywordChart.update();
GM_setValue('keywordData', JSON.stringify(this.state.keywordChart.data));
},
updateProgress: function() {
if (this.state.totalPages === 0) {
this.elements.progressBar.value = 0;
this.elements.progressText.innerText = '0%';
} else {
const percent = Math.min(((this.state.currentPage - 1) / this.state.totalPages) * 100, 100);
this.elements.progressBar.value = percent;
this.elements.progressText.innerText = `${Math.round(percent)}%`;
if (this.state.currentPage > this.state.totalPages) {
this.stopCrawling();
Logger.log('🎉 크롤링이 완료되었습니다.', 'success');
GM_notification({
text: '크롤링이 완료되었습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
}
}
},
updateElapsedTime: function() {
if (!this.state.startTime) return;
const now = Date.now();
const elapsed = Math.floor((now - this.state.startTime) / 1000);
this.elements.elapsedTimeElem.innerText = Utils.formatTime(elapsed);
const estimatedTotal = this.state.totalPages * 0.1; // 예측: 각 페이지 100ms = 0.1초
const remaining = Math.max(estimatedTotal - elapsed, 0);
this.elements.remainingTimeElem.innerText = Utils.formatTime(remaining);
},
handleCrawlError: function(page, retriesLeft) {
if (retriesLeft > 0 && this.state.isRunning) {
Logger.log(`🔄 페이지 ${page} 재시도 (${retriesLeft}회 남음).`, 'warning');
setTimeout(async () => {
try {
const url = this.constructURL(page);
const response = await this.fetchPage(url);
if (response.status === 200) {
Logger.log(`✅ 페이지 ${page} 재시도 성공.`, 'success');
await this.crawlPage();
} else {
this.handleCrawlError(page, retriesLeft - 1);
}
} catch (err) {
this.handleCrawlError(page, retriesLeft - 1);
}
}, this.state.retryInterval);
} else {
Logger.log(`❌ 페이지 ${page} 로드 실패: 최대 재시도 횟수 초과.`, 'error');
this.state.currentPage++;
this.elements.currentPageElem.innerText = this.state.currentPage;
setTimeout(this.crawlPage.bind(this), 0);
}
},
addResultRow: function(row) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${Utils.escapeHTML(row.title)}</td>
<td><a href="${Utils.escapeHTML(row.link)}" target="_blank">${Utils.escapeHTML(row.link)}</a></td>
<td>${Utils.escapeHTML(row.description)}</td>
<td>${row.image}</td>
<td>${row.htmlLink}</td>
<td>${row.whoisInfo}</td>
<td>${row.pageLoadTime}</td>
<td>${row.htmlLink !== 'N/A' ? row.htmlLink : 'N/A'}</td>
`;
this.elements.resultsBody.appendChild(tr);
this.addHTMLViewEventListeners();
},
exportResults: function() {
if (this.state.results.length === 0) {
alert('내보낼 결과가 없습니다.');
return;
}
const format = prompt('내보낼 형식을 선택하세요 (xlsx, csv, json, pdf):', 'xlsx');
if (!format) return;
if (format.toLowerCase() === 'xlsx') {
const ws = XLSX.utils.json_to_sheet(this.state.results);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "결과");
XLSX.writeFile(wb, "크롤링_결과.xlsx");
Logger.log('💾 결과를 "크롤링_결과.xlsx" 파일로 내보냈습니다.', 'success');
GM_notification({
text: '결과를 "크롤링_결과.xlsx" 파일로 내보냈습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
} else if (format.toLowerCase() === 'csv') {
const csv = [
["사이트 이름","주소","설명","이미지","HTML 링크","WHOIS 정보","페이지 로딩 시간 (ms)"],
...this.state.results.map(row => `"${Utils.escapeCSV(row.title)}","${Utils.escapeCSV(row.link)}","${Utils.escapeCSV(row.description)}","${Utils.escapeCSV(row.image)}","${Utils.escapeCSV(row.htmlLink)}","${Utils.escapeCSV(row.whoisInfo)}","${Utils.escapeCSV(row.pageLoadTime)}"`)
].join('\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '크롤링_결과.csv';
a.click();
Logger.log('💾 결과를 "크롤링_결과.csv" 파일로 내보냈습니다.', 'success');
GM_notification({
text: '결과를 "크롤링_결과.csv" 파일로 내보냈습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
} else if (format.toLowerCase() === 'json') {
const json = JSON.stringify(this.state.results, null, 2);
const blob = new Blob([json], { type: 'application/json;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '크롤링_결과.json';
a.click();
Logger.log('💾 결과를 "크롤링_결과.json" 파일로 내보냈습니다.', 'success');
GM_notification({
text: '결과를 "크롤링_결과.json" 파일로 내보냈습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
} else if (format.toLowerCase() === 'pdf') {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
let y = 10;
this.state.results.forEach((row, index) => {
doc.text(`${index + 1}. ${row.title}`, 10, y);
y += 7;
doc.text(`주소: ${row.link}`, 10, y);
y += 7;
doc.text(`설명: ${row.description}`, 10, y);
y += 7;
if (y > 270) {
doc.addPage();
y = 10;
}
});
doc.save('크롤링_결과.pdf');
Logger.log('💾 결과를 "크롤링_결과.pdf" 파일로 내보냈습니다.', 'success');
GM_notification({
text: '결과를 "크롤링_결과.pdf" 파일로 내보냈습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
} else {
alert('지원하지 않는 형식입니다.');
}
},
addHTMLViewEventListeners: function() {
const buttons = UI.container.querySelectorAll('.view-html-btn');
buttons.forEach(button => {
button.addEventListener('click', async () => {
const url = decodeURIComponent(button.getAttribute('data-url'));
Logger.log(`📄 HTML을 불러오는 중: ${url}`);
try {
const response = await fetch(url);
const htmlText = await response.text();
Controller.elements.htmlContent.textContent = htmlText;
hljs.highlightElement(Controller.elements.htmlContent); // 구문 강조
UI.container.querySelector("#htmlModal").style.display = "block";
Logger.log(`✅ HTML 불러오기 완료: ${url}`, 'success');
} catch (err) {
Logger.log(`❌ HTML 불러오기 실패: ${url}`, 'error');
Controller.elements.htmlContent.textContent = 'HTML을 불러오는 데 실패했습니다.';
UI.container.querySelector("#htmlModal").style.display = "block";
}
});
});
},
analyzeKeywords: function(text) {
const words = text.toLowerCase().match(/\b\w+\b/g);
if (!words) return;
words.forEach(word => {
if (word.length < 2) return;
this.state.keywordFrequency[word] = (this.state.keywordFrequency[word] || 0) + 1;
});
// Update keyword chart
this.updateKeywordChart();
},
initializeCharts: function() {
// Already initialized in Controller
},
updateChart: function() {
this.state.crawlChart.data.labels = Array.from(this.state.visitedLinks.keys());
this.state.crawlChart.data.datasets[0].data = Array.from(this.state.visitedLinks.values());
this.state.crawlChart.update();
GM_setValue('crawlerData', JSON.stringify(this.state.crawlChart.data));
},
updateKeywordChart: function() {
this.state.keywordChart.data.labels = Object.keys(this.state.keywordFrequency);
this.state.keywordChart.data.datasets[0].data = Object.values(this.state.keywordFrequency);
this.state.keywordChart.update();
GM_setValue('keywordData', JSON.stringify(this.state.keywordChart.data));
},
updateProgress: function() {
if (this.state.totalPages === 0) {
this.elements.progressBar.value = 0;
this.elements.progressText.innerText = '0%';
} else {
const percent = Math.min(((this.state.currentPage - 1) / this.state.totalPages) * 100, 100);
this.elements.progressBar.value = percent;
this.elements.progressText.innerText = `${Math.round(percent)}%`;
if (this.state.currentPage > this.state.totalPages) {
this.stopCrawling();
Logger.log('🎉 크롤링이 완료되었습니다.', 'success');
GM_notification({
text: '크롤링이 완료되었습니다.',
title: '웹 크롤러 7.2',
timeout: 3000
});
}
}
},
updateElapsedTime: function() {
if (!this.state.startTime) return;
const now = Date.now();
const elapsed = Math.floor((now - this.state.startTime) / 1000);
this.elements.elapsedTimeElem.innerText = Utils.formatTime(elapsed);
const estimatedTotal = this.state.totalPages * 0.1; // 예측: 각 페이지 100ms = 0.1초
const remaining = Math.max(estimatedTotal - elapsed, 0);
this.elements.remainingTimeElem.innerText = Utils.formatTime(remaining);
},
handleCrawlError: function(page, retriesLeft) {
if (retriesLeft > 0 && this.state.isRunning) {
Logger.log(`🔄 페이지 ${page} 재시도 (${retriesLeft}회 남음).`, 'warning');
setTimeout(async () => {
try {
const url = this.constructURL(page);
const response = await this.fetchPage(url);
if (response.status === 200) {
Logger.log(`✅ 페이지 ${page} 재시도 성공.`, 'success');
await this.crawlPage();
} else {
this.handleCrawlError(page, retriesLeft - 1);
}
} catch (err) {
this.handleCrawlError(page, retriesLeft - 1);
}
}, this.state.retryInterval);
} else {
Logger.log(`❌ 페이지 ${page} 로드 실패: 최대 재시도 횟수 초과.`, 'error');
this.state.currentPage++;
this.elements.currentPageElem.innerText = this.state.currentPage;
setTimeout(this.crawlPage.bind(this), 0);
}
},
restoreState: function() {
const savedState = GM_getValue('crawlerState', null);
if (savedState && savedState.isRunning) {
this.state = { ...this.state, ...savedState };
// 결과 테이블 복원
this.elements.resultsBody.innerHTML = '';
this.state.results.forEach(row => {
this.addResultRow(row);
});
// 차트 복원
this.updateChart();
this.updateKeywordChart();
// 상태 업데이트
this.elements.visitedCountElem.innerText = this.state.visitedLinks.size.toString();
this.elements.currentPageElem.innerText = this.state.currentPage;
this.elements.totalPagesElem.innerText = this.state.totalPages;
// 로그 복원
Logger.loadLogs();
// 크롤링 재개
if (this.state.isRunning && !this.state.isPaused) {
this.state.elapsedInterval = setInterval(this.updateElapsedTime.bind(this), 1000);
this.crawlPage();
}
}
},
saveState: function() {
const stateToSave = {
isRunning: this.state.isRunning,
isPaused: this.state.isPaused,
currentPage: this.state.currentPage,
totalPages: this.state.totalPages,
results: this.state.results,
keywordFrequency: this.state.keywordFrequency,
visitedLinks: Array.from(this.state.visitedLinks.entries()),
filterPatterns: this.state.filterPatterns,
excludeDomains: this.state.excludeDomains,
duplicateThreshold: this.state.duplicateThreshold,
retryAttempts: this.state.retryAttempts,
retryInterval: this.state.retryInterval,
startTime: this.state.startTime
};
GM_setValue('crawlerState', stateToSave);
}
};
// Initialize UI and Controller
UI.initialize();
Controller.init();
// Periodically save state
setInterval(Controller.saveState.bind(Controller), 5000);
})();
이 개선된 스크립트는 코드의 가독성과 유지 관리를 용이하게 하며, 사용자 경험을 크게 향상시킵니다. 추가적인 기능이나 최적화가 필요하다면, 모듈별로 세분화된 접근 방식을 통해 쉽게 확장할 수 있습니다.