안녕하세요! 제공해주신 Advanced Web Crawler Enhanced Pro Optimized v6.0.4 사용자의 요구사항을 반영하여 스크립트를 개선해드리겠습니다. 주요 개선사항은 다음과 같습니다:
아래는 개선된 전체 스크립트입니다.
javascript Copy code
// ==UserScript==
// @name Advanced Web Crawler Enhanced Pro Optimized v6.1.0
// @namespace http://tampermonkey.net/
// @version 6.1.0
// @description Optimized and enhanced version of Advanced Web Crawler with improved user agent rotation, modular code structure, enhanced logging, and better user experience.
// @author Your Name
// @match https://www.google.com/search*
// @match https://www.bing.com/search*
// @match https://search.yahoo.com/search*
// @match https://duckduckgo.com/*
// @match https://www.baidu.com/s*
// @match https://www.yandex.com/search/*
// @match https://search.naver.com/search*
// @match https://search.daum.net/search*
// @match https://www.ask.com/*
// @match https://www.ecosia.org/search*
// @match https://www.startpage.com/*
// @match https://searx.me/*
// @match https://www.dogpile.com/*
// @match https://www.bing.com/images*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @connect *
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// @require https://cdn.jsdelivr.net/npm/chart.js
// @require https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js
// ==/UserScript==
(function() {
'use strict';
/************* Constants Module *************/
const Constants = {
DEFAULT_SETTINGS: {
delay: 2000,
delayRandom: 500,
maxPages: 3,
userAgents: [
'AdvancedWebCrawler/6.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'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) AppleWebKit/605.1.15',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
'Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
],
blacklist: [],
whitelist: [],
contentTypes: {
include: ['text/html'],
exclude: ['application/pdf', 'image/jpeg', 'image/png', 'video/mp4']
},
timeout: 8000,
includeKeywords: [],
excludeKeywords: [],
language: [],
minWordCount: 100,
maxWordCount: 10000,
maxDepth: 2,
proxy: '',
regexInclude: [],
regexExclude: [],
dataFields: {
name: true,
url: true,
description: true,
html: true,
category: true,
quality: true,
language: true,
wordCount: true,
metaTags: false,
headings: false
},
schedule: {
enabled: false,
startTime: '00:00',
interval: 3600000 // in ms
},
searchEngines: {
google: true,
bing: true,
yahoo: true,
duckduckgo: true,
baidu: true,
yandex: true,
naver: true,
daum: true,
ask: true,
ecosia: true,
startpage: true,
searx: true,
dogpile: true,
bingimages: true
},
retryAttempts: 3,
retryDelay: 2000,
respectRobots: true,
maxConcurrentRequests: 3,
dataVisualization: true,
exportFormats: {
csv: true,
json: true,
xml: true,
xls: true
},
advancedLogging: true,
enableCaptchas: false
},
LOG_LEVELS: {
INFO: 'info',
WARNING: 'warning',
ERROR: 'error',
SUCCESS: 'success'
},
LANGUAGE_OPTIONS: [
{ value: 'en', text: '영어 (en)' }, { value: 'ko', text: '한국어 (ko)' },
{ value: 'zh', text: '중국어 (zh)' }, { value: 'ja', text: '일본어 (ja)' },
{ value: 'ru', text: '러시아어 (ru)' }, { value: 'es', text: '스페인어 (es)' },
{ value: 'fr', text: '프랑스어 (fr)' }, { value: 'de', text: '독일어 (de)' },
{ value: 'it', text: '이탈리아어 (it)' }, { value: 'pt', text: '포르투갈어 (pt)' },
{ value: 'ar', text: '아랍어 (ar)' }, { value: 'hi', text: '힌디어 (hi)' },
{ value: 'bn', text: '벵골어 (bn)' }, { value: 'pa', text: '펀자브어 (pa)' },
{ value: 'nl', text: '네덜란드어 (nl)' }, { value: 'sv', text: '스웨덴어 (sv)' },
{ value: 'tr', text: '터키어 (tr)' }, { value: 'vi', text: '베트남어 (vi)' },
{ value: 'pl', text: '폴란드어 (pl)' }, { value: 'th', text: '태국어 (th)' }
],
DATA_FIELDS: {
name: '사이트 이름',
url: '주소',
description: '설명',
html: '📄 HTML 내용',
category: '분류',
quality: '품질점수',
language: '언어',
wordCount: '단어 수',
metaTags: '메타 태그',
headings: '헤딩'
}
};
/************* Settings Module *************/
const SettingsModule = (function() {
let settings = {};
function loadSettings() {
settings = Object.assign({}, Constants.DEFAULT_SETTINGS, {
delay: parseInt(GM_getValue('delay', Constants.DEFAULT_SETTINGS.delay), 10),
delayRandom: parseInt(GM_getValue('delayRandom', Constants.DEFAULT_SETTINGS.delayRandom), 10),
maxPages: parseInt(GM_getValue('maxPages', Constants.DEFAULT_SETTINGS.maxPages), 10),
userAgents: GM_getValue('userAgents', Constants.DEFAULT_SETTINGS.userAgents),
blacklist: GM_getValue('blacklist', Constants.DEFAULT_SETTINGS.blacklist),
whitelist: GM_getValue('whitelist', Constants.DEFAULT_SETTINGS.whitelist),
contentTypes: GM_getValue('contentTypes', Constants.DEFAULT_SETTINGS.contentTypes),
timeout: parseInt(GM_getValue('timeout', Constants.DEFAULT_SETTINGS.timeout), 10),
includeKeywords: GM_getValue('includeKeywords', Constants.DEFAULT_SETTINGS.includeKeywords),
excludeKeywords: GM_getValue('excludeKeywords', Constants.DEFAULT_SETTINGS.excludeKeywords),
regexInclude: GM_getValue('regexInclude', Constants.DEFAULT_SETTINGS.regexInclude),
regexExclude: GM_getValue('regexExclude', Constants.DEFAULT_SETTINGS.regexExclude),
language: GM_getValue('language', Constants.DEFAULT_SETTINGS.language),
minWordCount: parseInt(GM_getValue('minWordCount', Constants.DEFAULT_SETTINGS.minWordCount), 10),
maxWordCount: parseInt(GM_getValue('maxWordCount', Constants.DEFAULT_SETTINGS.maxWordCount), 10),
maxDepth: parseInt(GM_getValue('maxDepth', Constants.DEFAULT_SETTINGS.maxDepth), 10),
proxy: GM_getValue('proxy', Constants.DEFAULT_SETTINGS.proxy),
dataFields: GM_getValue('dataFields', Constants.DEFAULT_SETTINGS.dataFields),
schedule: GM_getValue('schedule', Constants.DEFAULT_SETTINGS.schedule),
searchEngines: GM_getValue('searchEngines', Constants.DEFAULT_SETTINGS.searchEngines),
retryAttempts: parseInt(GM_getValue('retryAttempts', Constants.DEFAULT_SETTINGS.retryAttempts), 10),
retryDelay: parseInt(GM_getValue('retryDelay', Constants.DEFAULT_SETTINGS.retryDelay), 10),
respectRobots: GM_getValue('respectRobots', Constants.DEFAULT_SETTINGS.respectRobots),
maxConcurrentRequests: parseInt(GM_getValue('maxConcurrentRequests', Constants.DEFAULT_SETTINGS.maxConcurrentRequests), 10),
dataVisualization: GM_getValue('dataVisualization', Constants.DEFAULT_SETTINGS.dataVisualization),
exportFormats: GM_getValue('exportFormats', Constants.DEFAULT_SETTINGS.exportFormats),
advancedLogging: GM_getValue('advancedLogging', Constants.DEFAULT_SETTINGS.advancedLogging),
enableCaptchas: GM_getValue('enableCaptchas', Constants.DEFAULT_SETTINGS.enableCaptchas),
customKeywords: GM_getValue('customKeywords', {})
});
// Ensure userAgents is an array
if (!Array.isArray(settings.userAgents)) settings.userAgents = Constants.DEFAULT_SETTINGS.userAgents;
// Ensure dataFields is an object
if (typeof settings.dataFields !== 'object') settings.dataFields = Constants.DEFAULT_SETTINGS.dataFields;
}
function saveSettings(newSettings) {
settings = Object.assign({}, settings, newSettings);
// Persist each setting
GM_setValue('delay', settings.delay);
GM_setValue('delayRandom', settings.delayRandom);
GM_setValue('maxPages', settings.maxPages);
GM_setValue('userAgents', settings.userAgents);
GM_setValue('blacklist', settings.blacklist);
GM_setValue('whitelist', settings.whitelist);
GM_setValue('contentTypes', settings.contentTypes);
GM_setValue('timeout', settings.timeout);
GM_setValue('includeKeywords', settings.includeKeywords);
GM_setValue('excludeKeywords', settings.excludeKeywords);
GM_setValue('regexInclude', settings.regexInclude);
GM_setValue('regexExclude', settings.regexExclude);
GM_setValue('language', settings.language);
GM_setValue('minWordCount', settings.minWordCount);
GM_setValue('maxWordCount', settings.maxWordCount);
GM_setValue('maxDepth', settings.maxDepth);
GM_setValue('proxy', settings.proxy);
GM_setValue('dataFields', settings.dataFields);
GM_setValue('schedule', settings.schedule);
GM_setValue('searchEngines', settings.searchEngines);
GM_setValue('retryAttempts', settings.retryAttempts);
GM_setValue('retryDelay', settings.retryDelay);
GM_setValue('respectRobots', settings.respectRobots);
GM_setValue('maxConcurrentRequests', settings.maxConcurrentRequests);
GM_setValue('dataVisualization', settings.dataVisualization);
GM_setValue('exportFormats', settings.exportFormats);
GM_setValue('advancedLogging', settings.advancedLogging);
GM_setValue('enableCaptchas', settings.enableCaptchas);
GM_setValue('customKeywords', settings.customKeywords);
}
function resetSettings() {
settings = JSON.parse(JSON.stringify(Constants.DEFAULT_SETTINGS));
// Remove all saved settings
Object.keys(Constants.DEFAULT_SETTINGS).forEach(key => GM_deleteValue(key));
// Re-initialize defaults
loadSettings();
}
function getSettings() {
return settings;
}
loadSettings();
return {
loadSettings,
saveSettings,
resetSettings,
getSettings
};
})();
/************* Logging Module *************/
const LoggingModule = (function() {
let logs = [];
function loadLogs() {
logs = GM_getValue('logs', []);
}
function saveLogs() {
GM_setValue('logs', logs);
}
function log(message, level = Constants.LOG_LEVELS.INFO) {
const timestamp = new Date().toLocaleString();
const logEntry = { timestamp, message, level };
logs.push(logEntry);
saveLogs();
UIModule.updateLogsUI(logEntry);
if (SettingsModule.getSettings().advancedLogging) {
const styles = {
[Constants.LOG_LEVELS.INFO]: 'color: blue;',
[Constants.LOG_LEVELS.WARNING]: 'color: orange;',
[Constants.LOG_LEVELS.ERROR]: 'color: red;',
[Constants.LOG_LEVELS.SUCCESS]: 'color: green; font-weight: bold;'
};
console.log(`%c[${timestamp}] [${level.toUpperCase()}] ${message}`, styles[level] || '');
}
// Browser Notifications
if (['error', 'success'].includes(level)) {
NotificationsModule.notify(`${level.toUpperCase()}: ${message}`);
}
}
function getLogs() {
return logs;
}
function clearLogs() {
logs = [];
saveLogs();
UIModule.clearLogsUI();
}
loadLogs();
return {
log,
getLogs,
clearLogs
};
})();
/************* Notifications Module *************/
const NotificationsModule = (function() {
function requestPermission() {
if (Notification.permission === 'default') {
Notification.requestPermission();
}
}
function notify(message) {
if (Notification.permission === 'granted') {
new Notification('Advanced Web Crawler', { body: message });
}
}
// Initialize
requestPermission();
return {
notify
};
})();
/************* UI Module *************/
const UIModule = (function() {
function createUI() {
const style = `
#crawler-container {
position: fixed;
top: 20px;
right: 20px;
width: 400px;
height: 500px;
background: #fff;
border: 1px solid #ccc;
z-index: 10000;
font-family: Arial, sans-serif;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
overflow: auto;
resize: both;
border-radius: 8px;
min-width: 300px;
min-height: 300px;
}
#crawler-header {
display: flex;
justify-content: space-between;
align-items: center;
background: #f1f1f1;
border-bottom: 1px solid #ccc;
padding: 5px 10px;
cursor: move;
}
#crawler-minimize {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
}
#crawler-tabs { display: flex; background: #f1f1f1; border-bottom: 1px solid #ccc; }
.crawler-tab { flex: 1; padding: 10px; text-align: center; cursor: pointer; font-weight: bold; }
.crawler-tab.active { background: #ddd; }
#crawler-content { padding: 10px; overflow: auto; height: calc(100% - 50px); }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #f2f2f2; cursor: pointer; }
tr:hover { background-color: #f5f5f5; }
.progress-bar { width: 100%; background-color: #f3f3f3; border: 1px solid #ccc; border-radius: 5px; overflow: hidden; margin-bottom: 10px; }
.progress-bar-fill { height: 20px; background-color: #4caf50; width: 0%; transition: width 0.2s; }
.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); }
.modal-content { background-color: #fff; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 80%; max-height: 80%; overflow-y: auto; border-radius: 8px; }
.close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; }
.control-buttons { margin: 10px 0; }
.control-buttons button { padding: 8px 12px; margin-right: 8px; cursor: pointer; border: none; background-color: #4caf50; color: white; border-radius: 4px; font-size: 14px; }
.control-buttons button:disabled { background-color: #a5d6a7; cursor: not-allowed; }
.status-text { margin-top: 10px; font-weight: bold; font-size: 14px; }
.settings-section { margin-bottom: 15px; }
.settings-section label { display: block; margin-bottom: 5px; font-weight: bold; }
.settings-section input[type="text"], .settings-section input[type="number"], .settings-section textarea, .settings-section select { width: 100%; padding: 5px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
.settings-section .checkbox-group { display: flex; flex-wrap: wrap; }
.settings-section .checkbox-group label { margin-right: 10px; font-size: 14px; }
.settings-section .radio-group { display: flex; flex-wrap: wrap; }
.settings-section .radio-group label { margin-right: 10px; font-size: 14px; }
.tooltip { position: relative; display: inline-block; cursor: help; font-size: 14px; }
.tooltip .tooltiptext { visibility: hidden; width: 220px; background-color: #555; color: #fff; text-align: center; border-radius: 6px; padding: 5px; position: absolute; z-index: 1; bottom: 125%; left: 50%; margin-left: -110px; opacity: 0; transition: opacity 0.3s; }
.tooltip:hover .tooltiptext { visibility: visible; opacity: 1; }
#crawler-container::-webkit-resizer { background: #f1f1f1; border: none; }
#data-visualization { margin-top: 20px; }
#data-chart { width: 100%; height: 300px; }
#modal-html-content { white-space: pre-wrap; word-wrap: break-word; background-color: #f9f9f9; padding: 10px; border-radius: 4px; }
#crawler-tabs .crawler-tab:last-child { flex: 1; }
#previous-crawls { margin-top: 20px; }
#previous-crawls table { width: 100%; }
#previous-crawls th, #previous-crawls td { padding: 5px; }
#reset-data { background-color: #f44336; }
/* Loading Spinner */
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 2s linear infinite;
display: inline-block;
vertical-align: middle;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Error Message Styling */
.error-message {
color: red;
font-weight: bold;
margin-top: 10px;
}
/* Success Message Styling */
.success-message {
color: green;
font-weight: bold;
margin-top: 10px;
}
`;
$('head').append(`<style>${style}</style>`);
const container = $(`
<div id="crawler-container">
<div id="crawler-header">
<div id="crawler-tabs">
<div class="crawler-tab" data-tab="logs" title="로그 보기">📜 로그</div>
<div class="crawler-tab" data-tab="data" title="수집된 데이터 보기">📊 데이터</div>
<div class="crawler-tab" data-tab="settings" title="설정 변경">⚙️ 설정</div>
<div class="crawler-tab" data-tab="previous-crawls" title="이전 크롤링 기록">📁 기록</div>
</div>
<button id="crawler-minimize" title="창 최소화">─</button>
</div>
<div id="crawler-content">
<div id="tab-logs" style="display: block;">
<div class="progress-bar">
<div class="progress-bar-fill" style="width: 0%;"></div>
</div>
<div class="status-text">진행률: 0.00% (0/${SettingsModule.getSettings().maxPages} 페이지)</div>
<div class="control-buttons">
<button id="start-crawling" title="크롤링을 시작합니다.">▶ 시작</button>
<button id="stop-crawling" title="크롤링을 중지합니다." disabled>■ 중지</button>
${SettingsModule.getSettings().exportFormats.csv ? `<button id="download-csv" title="CSV 다운로드">📥 CSV</button>` : ''}
${SettingsModule.getSettings().exportFormats.json ? `<button id="download-json" title="JSON 다운로드">📥 JSON</button>` : ''}
${SettingsModule.getSettings().exportFormats.xml ? `<button id="download-xml" title="XML 다운로드">📥 XML</button>` : ''}
${SettingsModule.getSettings().exportFormats.xls ? `<button id="download-xls" title="XLS 다운로드">📥 XLS</button>` : ''}
<button id="reset-data" title="모든 크롤링 데이터를 초기화합니다.">🗑️ 초기화</button>
</div>
<div id="log-messages" style="height: 200px; overflow-y: auto; background: #f9f9f9; padding: 10px; border: 1px solid #ccc; border-radius: 4px;">
로그 내용이 여기에 표시됩니다.
</div>
<div id="error-message" class="error-message" style="display: none;"></div>
<div id="success-message" class="success-message" style="display: none;"></div>
</div>
<div id="tab-data" style="display: none;">
<input type="text" id="search-filter" placeholder="검색 필터..." style="width: 100%; padding: 5px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px;">
<table>
<thead>
<tr>
${Object.keys(Constants.DATA_FIELDS).map(field => SettingsModule.getSettings().dataFields[field] ? `<th data-sort="${field}">${Constants.DATA_FIELDS[field]}</th>` : '').join('')}
</tr>
</thead>
<tbody id="data-table-body"></tbody>
</table>
${SettingsModule.getSettings().dataVisualization ? `
<div id="data-visualization">
<h3>데이터 시각화</h3>
<canvas id="data-chart"></canvas>
</div>
` : ''}
</div>
<div id="tab-settings" style="display: none;">
<h3>설정</h3>
<div class="settings-section">
<label for="delay-input">크롤링 딜레이 (ms):
<span class="tooltip">ℹ️
<span class="tooltiptext">기본 딜레이과 딜레이 랜덤 값을 조합하여 요청 사이의 딜레이를 설정합니다.</span>
</span>
</label>
<input type="number" id="delay-input" value="${SettingsModule.getSettings().delay}" min="500" step="500">
</div>
<div class="settings-section">
<label for="delay-random-input">딜레이 랜덤 범위 (ms):
<span class="tooltip">ℹ️
<span class="tooltiptext">딜레이에 무작위 요소를 추가하여 보다 자연스러운 요청을 합니다.</span>
</span>
</label>
<input type="number" id="delay-random-input" value="${SettingsModule.getSettings().delayRandom}" min="0" step="500">
</div>
<div class="settings-section">
<label for="max-pages-input">최대 크롤링 페이지 수:
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링할 최대 페이지 수를 설정하세요.</span>
</span>
</label>
<input type="number" id="max-pages-input" value="${SettingsModule.getSettings().maxPages}" min="1">
</div>
<div class="settings-section">
<label for="user-agent-select">사용자 에이전트(User-Agent):
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링에 사용할 사용자 에이전트를 선택하거나 추가할 수 있습니다.</span>
</span>
</label>
<select id="user-agent-select" multiple size="6">
${SettingsModule.getSettings().userAgents.map((ua, idx) => `<option value="${idx}" ${idx === SettingsModule.getSettings().userAgentIndex ? 'selected' : ''}>${ua}</option>`).join('')}
</select>
<button id="add-user-agent" style="margin-top: 5px; padding: 5px 10px; background-color: #2196F3; color: white; border-radius: 4px; font-size: 12px;">추가</button>
<button id="remove-user-agent" style="margin-top: 5px; padding: 5px 10px; background-color: #f44336; color: white; border-radius: 4px; font-size: 12px;">제거</button>
</div>
<div class="settings-section">
<label>콘텐츠 유형:</label>
<div>
<strong>포함할 유형:</strong>
<textarea id="content-include-input" rows="3">${SettingsModule.getSettings().contentTypes.include.join(', ')}</textarea>
</div>
<div>
<strong>제외할 유형:</strong>
<textarea id="content-exclude-input" rows="3">${SettingsModule.getSettings().contentTypes.exclude.join(', ')}</textarea>
</div>
</div>
<div class="settings-section">
<label for="timeout-input">크롤링 타임아웃 (ms):
<span class="tooltip">ℹ️
<span class="tooltiptext">요청이 완료되기까지 기다릴 최대 시간을 밀리초 단위로 설정합니다.</span>
</span>
</label>
<input type="number" id="timeout-input" value="${SettingsModule.getSettings().timeout}" min="1000" step="1000">
</div>
<div class="settings-section">
<label for="include-keywords-input">포함할 키워드:
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링할 페이지에 반드시 포함되어야 하는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="include-keywords-input" rows="3">${SettingsModule.getSettings().includeKeywords.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="exclude-keywords-input">제외할 키워드:
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링할 페이지에 포함되면 안 되는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="exclude-keywords-input" rows="3">${SettingsModule.getSettings().excludeKeywords.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="regex-include-input">포함할 키워드 (정규 표현식):
<span class="tooltip">ℹ️
<span class="tooltiptext">포함할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="regex-include-input" rows="3">${SettingsModule.getSettings().regexInclude.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="regex-exclude-input">제외할 키워드 (정규 표현식):
<span class="tooltip">ℹ️
<span class="tooltiptext">제외할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="regex-exclude-input" rows="3">${SettingsModule.getSettings().regexExclude.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="language-select">언어 필터링:</label>
<select id="language-select" multiple size="10">
${Constants.LANGUAGE_OPTIONS.map(lang => `<option value="${lang.value}" ${SettingsModule.getSettings().language.includes(lang.value) ? 'selected' : ''}>${lang.text}</option>`).join('')}
</select>
</div>
<div class="settings-section">
<label for="min-word-count-input">최소 단어 수:
<span class="tooltip">ℹ️
<span class="tooltiptext">수집할 페이지의 최소 단어 수를 설정하세요.</span>
</span>
</label>
<input type="number" id="min-word-count-input" value="${SettingsModule.getSettings().minWordCount}" min="10" step="10">
<label for="max-word-count-input">최대 단어 수:
<span class="tooltip">ℹ️
<span class="tooltiptext">수집할 페이지의 최대 단어 수를 설정하세요.</span>
</span>
</label>
<input type="number" id="max-word-count-input" value="${SettingsModule.getSettings().maxWordCount}" min="100" step="100">
</div>
<div class="settings-section">
<label for="max-depth-input">최대 크롤링 깊이:
<span class="tooltip">ℹ️
<span class="tooltiptext">링크를 추적할 최대 깊이를 설정하세요.</span>
</span>
</label>
<input type="number" id="max-depth-input" value="${SettingsModule.getSettings().maxDepth}" min="1" step="1">
</div>
<div class="settings-section">
<label for="proxy-input">프록시 서버:
<span class="tooltip">ℹ️
<span class="tooltiptext">프록시 서버 주소를 입력하세요. 예: http://proxyserver:port</span>
</span>
</label>
<input type="text" id="proxy-input" value="${SettingsModule.getSettings().proxy}" placeholder="http://proxyserver:port">
</div>
<div class="settings-section">
<label>수집할 데이터 필드:</label>
<div class="checkbox-group">
${Object.keys(Constants.DATA_FIELDS).map(field => `<label><input type="checkbox" id="field-${field}" ${SettingsModule.getSettings().dataFields[field] ? 'checked' : ''}> ${Constants.DATA_FIELDS[field]}</label>`).join('')}
</div>
</div>
<div class="settings-section">
<label for="retry-attempts-input">재시도 횟수:
<span class="tooltip">ℹ️
<span class="tooltiptext">요청 실패 시 재시도할 횟수를 설정하세요.</span>
</span>
</label>
<input type="number" id="retry-attempts-input" value="${SettingsModule.getSettings().retryAttempts}" min="0" step="1">
<label for="retry-delay-input">재시도 딜레이 (ms):
<span class="tooltip">ℹ️
<span class="tooltiptext">재시도 시 대기할 시간을 밀리초 단위로 설정하세요.</span>
</span>
</label>
<input type="number" id="retry-delay-input" value="${SettingsModule.getSettings().retryDelay}" min="1000" step="500">
</div>
<div class="settings-section">
<label>크롤링 스케줄링:</label>
<div class="checkbox-group">
<label><input type="checkbox" id="schedule-enabled" ${SettingsModule.getSettings().schedule.enabled ? 'checked' : ''}> 스케줄링 활성화</label>
</div>
<div id="schedule-options" style="display: ${SettingsModule.getSettings().schedule.enabled ? 'block' : 'none'}; margin-top: 10px;">
<label for="start-time-input">시작 시간 (HH:MM):
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링을 시작할 시간을 설정하세요.</span>
</span>
</label>
<input type="time" id="start-time-input" value="${SettingsModule.getSettings().schedule.startTime}">
<label for="interval-input">크롤링 간격 (분):
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링 작업 간의 간격을 분 단위로 설정하세요.</span>
</span>
</label>
<input type="number" id="interval-input" value="${SettingsModule.getSettings().schedule.interval / 60000}" min="1" step="1">
</div>
</div>
<div class="settings-section">
<label>크롤링할 검색 엔진 선택:</label>
<div class="checkbox-group">
${Object.keys(SettingsModule.getSettings().searchEngines).map(engine => `<label><input type="checkbox" id="engine-${engine}" ${SettingsModule.getSettings().searchEngines[engine] ? 'checked' : ''}> ${capitalize(engine)}</label>`).join('')}
</div>
</div>
<div class="settings-section">
<label for="blacklist-input">블랙리스트 도메인:
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링에서 제외할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="blacklist-input" rows="5">${SettingsModule.getSettings().blacklist.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="whitelist-input">화이트리스트 도메인:
<span class="tooltip">ℹ️
<span class="tooltiptext">크롤링을 허용할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.</span>
</span>
</label>
<textarea id="whitelist-input" rows="5">${SettingsModule.getSettings().whitelist.join('\n')}</textarea>
</div>
<div class="settings-section">
<label for="respect-robots-checkbox">robots.txt 준수:
<span class="tooltip">ℹ️
<span class="tooltiptext">대상 사이트의 robots.txt 규칙을 준수하여 크롤링을 진행합니다.</span>
</span>
</label>
<input type="checkbox" id="respect-robots-checkbox" ${SettingsModule.getSettings().respectRobots ? 'checked' : ''}>
</div>
<div class="settings-section">
<label for="max-concurrent-requests-input">동시 요청 최대 수:
<span class="tooltip">ℹ️
<span class="tooltiptext">한 번에 요청할 수 있는 최대 동시 요청 수를 설정하세요.</span>
</span>
</label>
<input type="number" id="max-concurrent-requests-input" value="${SettingsModule.getSettings().maxConcurrentRequests}" min="1" step="1">
</div>
<div class="settings-section">
<label for="data-visualization-checkbox">데이터 시각화 활성화:
<span class="tooltip">ℹ️
<span class="tooltiptext">수집된 데이터를 시각화하여 그래프로 표시합니다.</span>
</span>
</label>
<input type="checkbox" id="data-visualization-checkbox" ${SettingsModule.getSettings().dataVisualization ? 'checked' : ''}>
</div>
<div class="settings-section">
<label for="enable-captchas-checkbox">CAPTCHA 처리 활성화:
<span class="tooltip">ℹ️
<span class="tooltiptext">CAPTCHA가 감지되었을 때 자동 처리를 활성화합니다. (제한적)</span>
</span>
</label>
<input type="checkbox" id="enable-captchas-checkbox" ${SettingsModule.getSettings().enableCaptchas ? 'checked' : ''}>
</div>
<div class="settings-section">
<label>데이터 내보내기 형식:</label>
<div class="checkbox-group">
${Object.keys(SettingsModule.getSettings().exportFormats).map(format => `<label><input type="checkbox" id="export-${format}" ${SettingsModule.getSettings().exportFormats[format] ? 'checked' : ''}> ${format.toUpperCase()}</label>`).join('')}
</div>
</div>
<div class="settings-section">
<label for="advanced-logging-checkbox">고급 로깅 활성화:
<span class="tooltip">ℹ️
<span class="tooltiptext">추가적인 로깅 정보를 활성화합니다.</span>
</span>
</label>
<input type="checkbox" id="advanced-logging-checkbox" ${SettingsModule.getSettings().advancedLogging ? 'checked' : ''}>
</div>
<div class="settings-section">
<label for="custom-keywords-input">사용자 지정 키워드 분류:
<span class="tooltip">ℹ️
<span class="tooltiptext">사용자 지정 키워드를 추가하여 데이터 분류를 향상시킵니다. 형식: 카테고리:키워드1,키워드2,...</span>
</span>
</label>
<textarea id="custom-keywords-input" rows="5">${formatCustomKeywords(SettingsModule.getSettings().customKeywords)}</textarea>
</div>
<button id="save-settings" style="margin-top: 10px; padding: 10px 20px; background-color: #4caf50; color: white; border-radius: 4px; font-size: 14px;">저장</button>
<button id="reset-settings" style="margin-top: 10px; padding: 10px 20px; background-color: #f44336; color: white; border-radius: 4px; font-size: 14px;">초기화</button>
</div>
<div id="tab-previous-crawls" style="display: none;">
<h3>이전 크롤링 기록</h3>
<button id="clear-previous-crawls" style="padding: 8px 12px; background-color: #f44336; color: white; border-radius: 4px; font-size: 14px; margin-bottom: 10px;">기록 초기화</button>
<table>
<thead>
<tr>
<th>날짜</th>
<th>크롤링 수</th>
<th>상태</th>
</tr>
</thead>
<tbody id="previous-crawls-body">
<!-- 이전 크롤링 기록이 여기에 추가됩니다. -->
</tbody>
</table>
</div>
</div>
<div id="html-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<pre id="modal-html-content"></pre>
</div>
</div>
</div>
`);
$('body').append(container);
// Event Listeners
$('#crawler-minimize').on('click', toggleMinimize);
$('.crawler-tab').on('click', switchTab);
$('#start-crawling').on('click', CrawlerModule.startCrawling);
$('#stop-crawling').on('click', CrawlerModule.stopCrawling);
$('#save-settings').on('click', saveSettings);
$('#reset-settings').on('click', SettingsModule.resetSettings.bind(SettingsModule));
$('#add-user-agent').on('click', addUserAgent);
$('#remove-user-agent').on('click', removeUserAgent);
$('#download-csv').on('click', CrawlerModule.downloadCSV);
$('#download-json').on('click', CrawlerModule.downloadJSON);
$('#download-xml').on('click', CrawlerModule.downloadXML);
$('#download-xls').on('click', CrawlerModule.downloadXLS);
$('#search-filter').on('input', filterData);
$('#clear-previous-crawls').on('click', clearPreviousCrawls);
$('#reset-data').on('click', resetData);
$('#schedule-enabled').on('change', toggleScheduleOptions);
$('#data-visualization-checkbox').on('change', toggleDataVisualization);
$('#enable-captchas-checkbox').on('change', toggleEnableCaptchas);
$('#advanced-logging-checkbox').on('change', toggleAdvancedLogging);
$('#respect-robots-checkbox').on('change', toggleRespectRobots);
$('.view-html').on('click', viewHTMLContent);
$('.close').on('click', () => $('#html-modal').hide());
$(window).on('click', function(e) { if (e.target.id === 'html-modal') $('#html-modal').hide(); });
// Initialize Previous Crawls UI
updatePreviousCrawlsUI();
// Make Draggable
makeDraggable();
}
function toggleMinimize() {
$('#crawler-content').toggle();
const isHidden = $('#crawler-content').is(':hidden');
$('#crawler-minimize').text(isHidden ? '☐' : '─');
LoggingModule.log(`크롤러 창이 ${isHidden ? '최소화' : '확대'}되었습니다.`, Constants.LOG_LEVELS.INFO);
}
function switchTab() {
const tab = $(this).data('tab');
$('.crawler-tab').removeClass('active');
$(this).addClass('active');
$('#crawler-content > div').hide();
$(`#tab-${tab}`).show();
SettingsModule.saveSettings({ currentTab: tab });
}
function saveSettings() {
// Input Validation
const settings = {};
const currentSettings = SettingsModule.getSettings();
settings.delay = parseInt($('#delay-input').val(), 10);
settings.delayRandom = parseInt($('#delay-random-input').val(), 10);
settings.maxPages = parseInt($('#max-pages-input').val(), 10);
settings.userAgentIndex = parseInt($('#user-agent-select').val(), 10) || 0;
settings.contentTypes = {
include: $('#content-include-input').val().split(',').map(ct => ct.trim()).filter(ct => ct),
exclude: $('#content-exclude-input').val().split(',').map(ct => ct.trim()).filter(ct => ct)
};
settings.timeout = parseInt($('#timeout-input').val(), 10);
settings.includeKeywords = $('#include-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw);
settings.excludeKeywords = $('#exclude-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw);
settings.regexInclude = $('#regex-include-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx);
settings.regexExclude = $('#regex-exclude-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx);
settings.language = $('#language-select').val() || [];
settings.minWordCount = parseInt($('#min-word-count-input').val(), 10);
settings.maxWordCount = parseInt($('#max-word-count-input').val(), 10);
settings.maxDepth = parseInt($('#max-depth-input').val(), 10);
settings.proxy = $('#proxy-input').val().trim() || '';
settings.dataFields = {};
Object.keys(Constants.DATA_FIELDS).forEach(field => {
settings.dataFields[field] = $(`#field-${field}`).is(':checked');
});
settings.retryAttempts = parseInt($('#retry-attempts-input').val(), 10);
settings.retryDelay = parseInt($('#retry-delay-input').val(), 10);
settings.schedule = {
enabled: $('#schedule-enabled').is(':checked'),
startTime: $('#start-time-input').val() || '00:00',
interval: parseInt($('#interval-input').val(), 10) * 60000 || 3600000
};
settings.searchEngines = {};
Object.keys(currentSettings.searchEngines).forEach(engine => {
settings.searchEngines[engine] = $(`#engine-${engine}`).is(':checked');
});
settings.blacklist = $('#blacklist-input').val().split('\n').map(d => d.trim()).filter(d => d);
settings.whitelist = $('#whitelist-input').val().split('\n').map(d => d.trim()).filter(d => d);
settings.respectRobots = $('#respect-robots-checkbox').is(':checked');
settings.maxConcurrentRequests = parseInt($('#max-concurrent-requests-input').val(), 10) || 3;
settings.dataVisualization = $('#data-visualization-checkbox').is(':checked');
settings.exportFormats = {
csv: $('#export-csv').is(':checked'),
json: $('#export-json').is(':checked'),
xml: $('#export-xml').is(':checked'),
xls: $('#export-xls').is(':checked')
};
settings.advancedLogging = $('#advanced-logging-checkbox').is(':checked');
settings.enableCaptchas = $('#enable-captchas-checkbox').is(':checked');
settings.customKeywords = parseCustomKeywords($('#custom-keywords-input').val());
// Validate Inputs
const isValid = validateSettings(settings);
if (!isValid) {
LoggingModule.log('설정값이 유효하지 않습니다. 올바른 값을 입력하세요.', Constants.LOG_LEVELS.ERROR);
return;
}
// Save Settings
SettingsModule.saveSettings(settings);
// Update UI
updateLogsUI();
if (settings.dataVisualization) renderChart();
else $('#data-visualization').hide();
// Schedule Crawling if Enabled
if (settings.schedule.enabled) {
CrawlerModule.scheduleCrawling();
}
LoggingModule.log('설정이 저장되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function validateSettings(settings) {
return !isNaN(settings.delay) && settings.delay >= 500 &&
!isNaN(settings.delayRandom) && settings.delayRandom >= 0 &&
!isNaN(settings.maxPages) && settings.maxPages >= 1 &&
!isNaN(settings.timeout) && settings.timeout >= 1000 &&
!isNaN(settings.minWordCount) && settings.minWordCount >= 10 &&
!isNaN(settings.maxWordCount) && settings.maxWordCount >= 100 &&
!isNaN(settings.maxDepth) && settings.maxDepth >= 1 &&
!isNaN(settings.retryAttempts) && settings.retryAttempts >= 0 &&
!isNaN(settings.retryDelay) && settings.retryDelay >= 1000 &&
(!settings.schedule.enabled || (!isNaN(settings.schedule.interval) && settings.schedule.interval >= 60000));
}
function addUserAgent() {
const ua = prompt("새 사용자 에이전트를 입력하세요:");
if (ua) {
const currentUA = SettingsModule.getSettings().userAgents;
currentUA.push(ua);
SettingsModule.saveSettings({ userAgents: currentUA });
updateUserAgentSelect();
LoggingModule.log('새 사용자 에이전트가 추가되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
}
function removeUserAgent() {
const selected = $('#user-agent-select').val();
if (selected && selected.length) {
let userAgents = SettingsModule.getSettings().userAgents;
selected.sort((a, b) => b - a).forEach(idx => { userAgents.splice(idx, 1); });
SettingsModule.saveSettings({ userAgents });
updateUserAgentSelect();
LoggingModule.log('선택한 사용자 에이전트가 제거되었습니다.', Constants.LOG_LEVELS.SUCCESS);
} else {
alert('제거할 사용자 에이전트를 선택하세요.');
}
}
function updateUserAgentSelect() {
const userAgents = SettingsModule.getSettings().userAgents;
const userAgentIndex = SettingsModule.getSettings().userAgentIndex;
$('#user-agent-select').empty();
userAgents.forEach((ua, idx) => {
$('#user-agent-select').append(`<option value="${idx}" ${idx === userAgentIndex ? 'selected' : ''}>${ua}</option>`);
});
}
function updateLogsUI(logEntry) {
const { timestamp, message, level } = logEntry;
$('#log-messages').append(`<div>[${timestamp}] [${level.toUpperCase()}] ${message}</div>`);
$('#log-messages').scrollTop($('#log-messages')[0].scrollHeight);
// Update progress bar and status text
const progress = CrawlerModule.getProgress();
$('.progress-bar-fill').css('width', `${progress.toFixed(2)}%`);
$('.status-text').text(`진행률: ${progress.toFixed(2)}% (${CrawlerModule.getCurrentPage()}/${CrawlerModule.getTotalPages()} 페이지)`);
// Show error or success messages
if (level === Constants.LOG_LEVELS.ERROR) {
$('#error-message').text(message).show();
setTimeout(() => { $('#error-message').fadeOut(); }, 5000);
}
if (level === Constants.LOG_LEVELS.SUCCESS) {
$('#success-message').text(message).show();
setTimeout(() => { $('#success-message').fadeOut(); }, 5000);
}
}
function clearLogsUI() {
$('#log-messages').empty();
$('.progress-bar-fill').css('width', `0%`);
$('.status-text').text(`진행률: 0.00% (${CrawlerModule.getCurrentPage()}/${CrawlerModule.getTotalPages()} 페이지)`);
}
function filterData() {
const keyword = $('#search-filter').val().toLowerCase();
CrawlerModule.filterData(keyword);
}
function resetData() {
if (confirm("모든 크롤링 데이터를 초기화하시겠습니까?")) {
CrawlerModule.resetData();
LoggingModule.log('크롤링 데이터가 초기화되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
}
function clearPreviousCrawls() {
if (confirm("이전 크롤링 기록을 모두 초기화하시겠습니까?")) {
CrawlerModule.clearPreviousCrawls();
LoggingModule.log('이전 크롤링 기록이 초기화되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
}
function toggleScheduleOptions() {
const isEnabled = $('#schedule-enabled').is(':checked');
$('#schedule-options').toggle(isEnabled);
}
function toggleDataVisualization() {
const isEnabled = $('#data-visualization-checkbox').is(':checked');
SettingsModule.saveSettings({ dataVisualization: isEnabled });
$('#data-visualization').toggle(isEnabled);
if (isEnabled) {
CrawlerModule.renderChart();
LoggingModule.log('데이터 시각화가 활성화되었습니다.', Constants.LOG_LEVELS.SUCCESS);
} else {
LoggingModule.log('데이터 시각화가 비활성화되었습니다.', Constants.LOG_LEVELS.INFO);
}
}
function toggleEnableCaptchas() {
const isEnabled = $('#enable-captchas-checkbox').is(':checked');
SettingsModule.saveSettings({ enableCaptchas: isEnabled });
LoggingModule.log('CAPTCHA 처리 설정이 변경되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function toggleAdvancedLogging() {
const isEnabled = $('#advanced-logging-checkbox').is(':checked');
SettingsModule.saveSettings({ advancedLogging: isEnabled });
LoggingModule.log('고급 로깅 설정이 변경되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function toggleRespectRobots() {
const isEnabled = $('#respect-robots-checkbox').is(':checked');
SettingsModule.saveSettings({ respectRobots: isEnabled });
LoggingModule.log('robots.txt 준수 설정이 변경되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function viewHTMLContent() {
const html = decodeURIComponent($(this).data('html'));
$('#modal-html-content').text(html);
$('#html-modal').show();
}
function updatePreviousCrawlsUI() {
const previousCrawls = CrawlerModule.getPreviousCrawls();
$('#previous-crawls-body').html(previousCrawls.map(crawl => `
<tr>
<td>${crawl.date}</td>
<td>${crawl.count}</td>
<td>${crawl.status}</td>
</tr>
`).join(''));
}
function makeDraggable() {
const container = document.getElementById('crawler-container');
const header = document.getElementById('crawler-header');
let isDragging = false;
let startX, startY, initialX, initialY;
header.onmousedown = function(e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
initialX = container.offsetLeft;
initialY = container.offsetTop;
document.onmousemove = drag;
document.onmouseup = stopDrag;
return false;
};
function drag(e) {
if (isDragging) {
let dx = e.clientX - startX;
let dy = e.clientY - startY;
container.style.left = (initialX + dx) + 'px';
container.style.top = (initialY + dy) + 'px';
}
}
function stopDrag() {
isDragging = false;
document.onmousemove = null;
document.onmouseup = null;
}
}
function formatCustomKeywords(ck) {
return Object.entries(ck).map(([cat, kws]) => `${cat}:${kws.join(',')}`).join('\n');
}
return {
createUI,
updateLogsUI,
clearLogsUI,
updatePreviousCrawlsUI,
formatCustomKeywords
};
})();
/************* Crawler Module *************/
const CrawlerModule = (function() {
let visitedUrls = new Set(JSON.parse(GM_getValue('visitedUrls', '[]')));
let data = JSON.parse(GM_getValue('data', '[]'));
let isCrawling = GM_getValue('isCrawling', false);
let currentPage = parseInt(GM_getValue('currentPage', '1'), 10);
let totalPages = parseInt(GM_getValue('totalPages', SettingsModule.getSettings().maxPages), 10);
let currentDepth = parseInt(GM_getValue('currentDepth', '0'), 10);
let activeRequests = 0;
let requestQueue = [];
let previousCrawls = JSON.parse(GM_getValue('previousCrawls', '[]'));
let dataChartInstance = null;
const searchEngineHandlers = {
google: {
extractResults: function(doc) {
const results = [];
doc.querySelectorAll('div.g, div[data-hveid]').forEach(item => {
const name = item.querySelector('h3')?.innerText.trim() || 'No Title';
const url = item.querySelector('a')?.href || '';
const desc = item.querySelector('.aCOpRe, .VwiC3b')?.innerText.trim() || 'No Description';
if (isValidURL(url)) results.push({ name, url, description: desc });
});
return results;
},
getNextPageUrl: function(doc) {
return doc.querySelector('a#pnnext')?.href || null;
}
},
bing: {
extractResults: function(doc) {
const results = [];
doc.querySelectorAll('.b_algo').forEach(item => {
const name = item.querySelector('h2')?.innerText.trim() || 'No Title';
const url = item.querySelector('h2 a')?.href || '';
const desc = item.querySelector('.b_caption p')?.innerText.trim() || 'No Description';
if (isValidURL(url)) results.push({ name, url, description: desc });
});
return results;
},
getNextPageUrl: function(doc) {
return doc.querySelector('a.sb_pagN')?.href || null;
}
},
yahoo: {
extractResults: function(doc) {
const results = [];
doc.querySelectorAll('.Sr').forEach(item => {
const name = item.querySelector('h3')?.innerText.trim() || 'No Title';
const url = item.querySelector('a')?.href || '';
const desc = item.querySelector('.compText a')?.innerText.trim() || 'No Description';
if (isValidURL(url)) results.push({ name, url, description: desc });
});
return results;
},
getNextPageUrl: function(doc) {
return doc.querySelector('a.next')?.href || null;
}
},
duckduckgo: {
extractResults: function(doc) {
const results = [];
doc.querySelectorAll('.result').forEach(item => {
const name = item.querySelector('.result__title')?.innerText.trim() || 'No Title';
const url = item.querySelector('.result__url')?.href || '';
const desc = item.querySelector('.result__snippet')?.innerText.trim() || 'No Description';
if (isValidURL(url)) results.push({ name, url, description: desc });
});
return results;
},
getNextPageUrl: function(doc) {
return doc.querySelector('a.result--more__btn')?.href || null;
}
},
// Add similar handlers for other search engines...
// Example:
searx: {
extractResults: function(doc) {
const results = [];
doc.querySelectorAll('.result').forEach(item => {
const name = item.querySelector('h3')?.innerText.trim() || 'No Title';
const url = item.querySelector('a')?.href || '';
const desc = item.querySelector('.result__snippet')?.innerText.trim() || 'No Description';
if (isValidURL(url)) results.push({ name, url, description: desc });
});
return results;
},
getNextPageUrl: function(doc) {
return doc.querySelector('a.next')?.href || null;
}
}
// Implement other search engines as needed
};
async function startCrawling() {
if (isCrawling) {
LoggingModule.log('이미 크롤링이 진행 중입니다.', Constants.LOG_LEVELS.WARNING);
return;
}
if (!Object.values(SettingsModule.getSettings().searchEngines).some(v => v)) {
LoggingModule.log('사용할 검색 엔진이 하나도 선택되지 않았습니다.', Constants.LOG_LEVELS.ERROR);
return;
}
isCrawling = true;
SettingsModule.saveSettings({ isCrawling });
LoggingModule.log('크롤링을 시작합니다.', Constants.LOG_LEVELS.INFO);
UIModule.toggleButtons(isCrawling);
currentPage = parseInt(GM_getValue('currentPage', '1'), 10);
totalPages = parseInt(GM_getValue('totalPages', SettingsModule.getSettings().maxPages), 10);
currentDepth = parseInt(GM_getValue('currentDepth', '0'), 10);
if (!previousCrawls.some(crawl => crawl.status === '진행 중')) {
previousCrawls.push({ date: new Date().toLocaleString(), count: 0, status: '진행 중' });
GM_setValue('previousCrawls', JSON.stringify(previousCrawls));
UIModule.updatePreviousCrawlsUI();
}
await crawlPage(currentDepth);
}
function stopCrawling() {
if (!isCrawling) {
LoggingModule.log('크롤링이 진행 중이지 않습니다.', Constants.LOG_LEVELS.WARNING);
return;
}
isCrawling = false;
SettingsModule.saveSettings({ isCrawling });
LoggingModule.log('크롤링이 중지되었습니다.', Constants.LOG_LEVELS.WARNING);
finalizeCrawl('중지됨');
UIModule.toggleButtons(isCrawling);
}
function toggleButtons(isCrawling) {
$('#start-crawling').prop('disabled', isCrawling);
$('#stop-crawling').prop('disabled', !isCrawling);
}
async function crawlPage(depth) {
try {
while (isCrawling && currentPage <= totalPages && depth <= SettingsModule.getSettings().maxDepth) {
LoggingModule.log(`페이지 ${currentPage} 크롤링 시작. (깊이: ${depth})`, Constants.LOG_LEVELS.INFO);
if (SettingsModule.getSettings().respectRobots && !(await checkRobotsTxt(window.location.href))) {
LoggingModule.log(`robots.txt에 의해 크롤링이 금지된 페이지: ${window.location.href}`, Constants.LOG_LEVELS.WARNING);
break;
}
const searchEngine = identifySearchEngine();
if (!searchEngine || !searchEngineHandlers[searchEngine]) {
LoggingModule.log(`지원되지 않는 검색 엔진: ${window.location.hostname}`, Constants.LOG_LEVELS.ERROR);
break;
}
const doc = document;
const handler = searchEngineHandlers[searchEngine];
const results = handler.extractResults(doc);
if (!results) {
LoggingModule.log('검색 결과를 찾을 수 없습니다.', Constants.LOG_LEVELS.ERROR);
break;
}
results.forEach(result => {
if (!isCrawling) return;
const { name, url, description } = result;
if (shouldSkipUrl(url, description)) return;
requestQueue.push({ url, depth });
if (activeRequests >= SettingsModule.getSettings().maxConcurrentRequests) return;
});
// Update previous crawls
if (previousCrawls.length && previousCrawls[previousCrawls.length -1].status === '진행 중') {
previousCrawls[previousCrawls.length -1].count += results.length;
GM_setValue('previousCrawls', JSON.stringify(previousCrawls));
UIModule.updatePreviousCrawlsUI();
}
await processQueue();
const progress = (currentPage / totalPages) * 100;
GM_setValue('progress', progress);
UIModule.updateLogsUI({timestamp: new Date().toLocaleString(), message: `진행률 업데이트: ${progress.toFixed(2)}%`, level: Constants.LOG_LEVELS.INFO});
if (currentPage < totalPages && isCrawling) {
const nextUrl = handler.getNextPageUrl(doc);
if (nextUrl) {
currentPage++;
GM_setValue('currentPage', currentPage);
depth++;
GM_setValue('currentDepth', depth);
LoggingModule.log(`다음 페이지로 이동: ${currentPage}`, Constants.LOG_LEVELS.INFO);
await dynamicDelay();
const nextPageContent = await fetchPageContent(nextUrl);
if (nextPageContent) {
updatePageContent(nextPageContent);
continue;
} else {
LoggingModule.log('다음 페이지 내용을 가져올 수 없습니다.', Constants.LOG_LEVELS.ERROR);
break;
}
} else {
LoggingModule.log('다음 페이지 링크를 찾을 수 없습니다.', Constants.LOG_LEVELS.ERROR);
break;
}
} else {
break;
}
}
if (isCrawling && currentPage > totalPages && activeRequests === 0 && requestQueue.length === 0) {
LoggingModule.log('크롤링이 완료되었습니다.', Constants.LOG_LEVELS.SUCCESS);
finalizeCrawl('완료됨');
isCrawling = false;
SettingsModule.saveSettings({ isCrawling });
UIModule.toggleButtons(isCrawling);
GM_setValue('progress', 100);
UIModule.updateLogsUI({timestamp: new Date().toLocaleString(), message: `진행률: 100% (${currentPage}/${totalPages} 페이지)`, level: Constants.LOG_LEVELS.INFO});
}
} catch (error) {
LoggingModule.log(`크롤링 중 오류 발생: ${error.message}`, Constants.LOG_LEVELS.ERROR);
finalizeCrawl('오류 발생');
}
}
async function processQueue() {
while (requestQueue.length && activeRequests < SettingsModule.getSettings().maxConcurrentRequests && isCrawling) {
const { url, depth } = requestQueue.shift();
activeRequests++;
handleRequest(url, depth).finally(() => {
activeRequests--;
processQueue();
});
}
}
async function handleRequest(url, depth) {
if (!isCrawling || visitedUrls.has(url)) return;
try {
const response = await fetchWithRetry(url, SettingsModule.getSettings().retryAttempts, SettingsModule.getSettings().retryDelay);
const contentType = getContentType(response);
if (!isContentTypeAllowed(contentType)) {
LoggingModule.log(`허용되지 않은 콘텐츠 유형(${contentType})의 URL: ${url}`, Constants.LOG_LEVELS.WARNING);
return;
}
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const text = doc.body ? doc.body.innerText : '';
if (SettingsModule.getSettings().enableCaptchas && detectCaptcha(doc)) {
await handleCaptcha(url);
return;
}
const wordCount = text.split(/\s+/).length;
if (wordCount < SettingsModule.getSettings().minWordCount || wordCount > SettingsModule.getSettings().maxWordCount) {
LoggingModule.log(`단어 수 조건에 맞지 않는 URL: ${url} (${wordCount} 단어)`, Constants.LOG_LEVELS.WARNING);
return;
}
const quality = evaluateContentQuality(text);
const lang = doc.documentElement.lang || 'unknown';
const category = classifyKeywords(text);
const meta = extractMetaTags(doc);
const headings = extractHeadings(doc);
if (category !== '기타' || quality > 100) {
const entry = { url, quality, language: lang, wordCount, category };
if (SettingsModule.getSettings().dataFields.name) entry.name = extractName(doc) || 'No Title';
if (SettingsModule.getSettings().dataFields.description) entry.description = extractDescription(doc) || 'No Description';
if (SettingsModule.getSettings().dataFields.html) entry.html = response.responseText;
if (SettingsModule.getSettings().dataFields.metaTags) entry.metaTags = meta;
if (SettingsModule.getSettings().dataFields.headings) entry.headings = headings;
data.push(entry);
GM_setValue('data', JSON.stringify(data));
updateDataUI();
LoggingModule.log(`데이터 수집 완료: ${url}`, Constants.LOG_LEVELS.SUCCESS);
if (SettingsModule.getSettings().dataVisualization) renderChart();
}
if (depth < SettingsModule.getSettings().maxDepth) {
const links = extractLinks(doc);
links.forEach(link => { if (!visitedUrls.has(link) && isValidURL(link)) requestQueue.push({ url: link, depth: depth + 1 }); });
}
} catch (error) {
LoggingModule.log(`데이터 수집 실패: ${url} - ${error.message}`, Constants.LOG_LEVELS.ERROR);
}
visitedUrls.add(url);
GM_setValue('visitedUrls', JSON.stringify([...visitedUrls]));
}
async function fetchWithRetry(url, attempts, delayMs) {
for (let i = 1; i <= attempts; i++) {
try {
return await GM_xmlhttpRequestPromise(url);
} catch (e) {
LoggingModule.log(`요청 실패 (${i}/${attempts}): ${url} - ${e.message}`, Constants.LOG_LEVELS.WARNING);
if (i < attempts) await delay(delayMs);
}
}
throw new Error('모든 재시도 시도가 실패했습니다.');
}
function isValidURL(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
function isContentTypeAllowed(ct) {
const { include, exclude } = SettingsModule.getSettings().contentTypes;
if (include.length && !include.includes(ct)) return false;
if (exclude.includes(ct)) return false;
return true;
}
function getContentType(res) {
const contentTypeHeader = res.responseHeaders.split('\n').find(h => h.toLowerCase().startsWith('content-type'));
return contentTypeHeader ? contentTypeHeader.split(':')[1].trim().split(';')[0] : '';
}
function evaluateContentQuality(text) {
// 간단한 품질 평가 로직 (예: 단어 수)
return text.split(/\s+/).length;
}
function extractMetaTags(doc) {
const metas = {};
doc.querySelectorAll('meta[name], meta[property]').forEach(meta => {
const name = meta.getAttribute('name') || meta.getAttribute('property');
const content = meta.getAttribute('content');
if (name && content) metas[name.toLowerCase()] = content;
});
return metas;
}
function extractHeadings(doc) {
const hs = [];
for (let i = 1; i <= 6; i++) {
doc.querySelectorAll(`h${i}`).forEach(h => hs.push(h.innerText.trim()));
}
return hs;
}
function extractName(doc) {
return doc.querySelector('title')?.innerText || 'No Title';
}
function extractDescription(doc) {
return doc.querySelector('meta[name="description"]')?.getAttribute('content') || 'No Description';
}
function extractLinks(doc) {
return Array.from(doc.querySelectorAll('a[href]')).map(a => a.href).filter(isValidURL);
}
function classifyKeywords(text) {
const kws = combineKeywords();
for (const [cat, keywords] of Object.entries(kws)) {
if (keywords.some(kw => text.includes(kw))) return cat;
}
return '기타';
}
function combineKeywords() {
const standard = {
'교육': ['학교', '교육', '학생', '교수', '강의'],
'기술': ['기술', '소프트웨어', '하드웨어', '프로그래밍', '개발'],
'뉴스': ['뉴스', '속보', '기사', '보도'],
'엔터테인먼트': ['영화', '음악', '연예', '게임', '드라마'],
'스포츠': ['축구', '야구', '농구', '경기', '토너먼트'],
'비즈니스': ['비즈니스', '경제', '주식', '투자', '시장'],
'건강': ['건강', '의료', '헬스', '운동', '영양'],
'과학': ['과학', '연구', '실험', '발견', '이론'],
'문학': ['소설', '시', '문학', '작가', '책'],
'여행': ['여행', '관광', '숙박', '비행기', '여권']
};
const custom = SettingsModule.getSettings().customKeywords || {};
for (const [cat, kws] of Object.entries(custom)) {
standard[cat] = standard[cat] ? [...new Set([...standard[cat], ...kws])] : kws;
}
return standard;
}
async function checkRobotsTxt(url) {
try {
const parsed = new URL(url);
const robotsUrl = `${parsed.origin}/robots.txt`;
const res = await fetchWithRetry(robotsUrl, 2, 1000);
return new RobotsParser(res.responseText).isAllowed(url, getRandomUserAgent());
} catch {
LoggingModule.log('robots.txt 확인 실패, 기본 허용.', Constants.LOG_LEVELS.WARNING);
return true;
}
}
class RobotsParser {
constructor(text) {
this.rules = [];
this.parse(text);
}
parse(text) {
let agents = [];
text.split('\n').forEach(line => {
const [key, ...val] = line.split(':').map(s => s.trim());
if (!key) return;
if (key.toLowerCase() === 'user-agent') {
agents = [val.join(':').toLowerCase()];
} else if (['disallow', 'allow'].includes(key.toLowerCase())) {
this.rules.push({ agents, type: key.toLowerCase(), path: val.join(':') });
}
});
}
isAllowed(url, ua) {
const path = new URL(url).pathname;
let allowed = true;
this.rules.forEach(rule => {
if (rule.agents.includes('*') || rule.agents.includes(ua.toLowerCase())) {
if (rule.type === 'disallow' && path.startsWith(rule.path)) allowed = false;
if (rule.type === 'allow' && path.startsWith(rule.path)) allowed = true;
}
});
return allowed;
}
}
async function fetchPageContent(url) {
try {
const res = await GM_xmlhttpRequestPromise(url);
return res.responseText;
} catch (error) {
LoggingModule.log(`페이지 내용을 가져오는 중 오류 발생: ${error.message}`, Constants.LOG_LEVELS.ERROR);
return null;
}
}
function updatePageContent(content) {
const parser = new DOMParser();
const doc = parser.parseFromString(content, 'text/html');
document.open();
document.write(content);
document.close();
}
async function processQueue() {
while (requestQueue.length && activeRequests < SettingsModule.getSettings().maxConcurrentRequests && isCrawling) {
const { url, depth } = requestQueue.shift();
activeRequests++;
handleRequest(url, depth).finally(() => {
activeRequests--;
processQueue();
});
}
}
async function handleRequest(url, depth) {
if (!isCrawling || visitedUrls.has(url)) return;
try {
const response = await fetchWithRetry(url, SettingsModule.getSettings().retryAttempts, SettingsModule.getSettings().retryDelay);
const contentType = getContentType(response);
if (!isContentTypeAllowed(contentType)) {
LoggingModule.log(`허용되지 않은 콘텐츠 유형(${contentType})의 URL: ${url}`, Constants.LOG_LEVELS.WARNING);
return;
}
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const text = doc.body ? doc.body.innerText : '';
if (SettingsModule.getSettings().enableCaptchas && detectCaptcha(doc)) {
await handleCaptcha(url);
return;
}
const wordCount = text.split(/\s+/).length;
if (wordCount < SettingsModule.getSettings().minWordCount || wordCount > SettingsModule.getSettings().maxWordCount) {
LoggingModule.log(`단어 수 조건에 맞지 않는 URL: ${url} (${wordCount} 단어)`, Constants.LOG_LEVELS.WARNING);
return;
}
const quality = evaluateContentQuality(text);
const lang = doc.documentElement.lang || 'unknown';
const category = classifyKeywords(text);
const meta = extractMetaTags(doc);
const headings = extractHeadings(doc);
if (category !== '기타' || quality > 100) {
const entry = { url, quality, language: lang, wordCount, category };
if (SettingsModule.getSettings().dataFields.name) entry.name = extractName(doc) || 'No Title';
if (SettingsModule.getSettings().dataFields.description) entry.description = extractDescription(doc) || 'No Description';
if (SettingsModule.getSettings().dataFields.html) entry.html = response.responseText;
if (SettingsModule.getSettings().dataFields.metaTags) entry.metaTags = meta;
if (SettingsModule.getSettings().dataFields.headings) entry.headings = headings;
data.push(entry);
GM_setValue('data', JSON.stringify(data));
updateDataUI();
LoggingModule.log(`데이터 수집 완료: ${url}`, Constants.LOG_LEVELS.SUCCESS);
if (SettingsModule.getSettings().dataVisualization) renderChart();
}
if (depth < SettingsModule.getSettings().maxDepth) {
const links = extractLinks(doc);
links.forEach(link => { if (!visitedUrls.has(link) && isValidURL(link)) requestQueue.push({ url: link, depth: depth + 1 }); });
}
} catch (error) {
LoggingModule.log(`데이터 수집 실패: ${url} - ${error.message}`, Constants.LOG_LEVELS.ERROR);
}
visitedUrls.add(url);
GM_setValue('visitedUrls', JSON.stringify([...visitedUrls]));
}
async function fetchWithRetry(url, attempts, delayMs) {
for (let i = 1; i <= attempts; i++) {
try {
return await GM_xmlhttpRequestPromise(url);
} catch (e) {
LoggingModule.log(`요청 실패 (${i}/${attempts}): ${url} - ${e.message}`, Constants.LOG_LEVELS.WARNING);
if (i < attempts) await delay(delayMs);
}
}
throw new Error('모든 재시도 시도가 실패했습니다.');
}
function getProgress() {
return (currentPage / totalPages) * 100;
}
function getCurrentPage() {
return currentPage;
}
function getTotalPages() {
return totalPages;
}
function resetData() {
data = [];
visitedUrls.clear();
GM_setValue('data', JSON.stringify(data));
GM_setValue('visitedUrls', JSON.stringify([...visitedUrls]));
updateDataUI();
}
function clearPreviousCrawls() {
previousCrawls = [];
GM_setValue('previousCrawls', JSON.stringify(previousCrawls));
UIModule.updatePreviousCrawlsUI();
}
function finalizeCrawl(status) {
if (previousCrawls.length) {
previousCrawls[previousCrawls.length -1].status = status;
GM_setValue('previousCrawls', JSON.stringify(previousCrawls));
UIModule.updatePreviousCrawlsUI();
}
}
function updateDataUI() {
const filter = $('#search-filter').val().toLowerCase();
const filtered = filter ? data.filter(item => Object.keys(SettingsModule.getSettings().dataFields).some(field => SettingsModule.getSettings().dataFields[field] && String(item[field]).toLowerCase().includes(filter))) : data;
const rows = filtered.map(item => `
<tr>
${Object.keys(Constants.DATA_FIELDS).map(field => SettingsModule.getSettings().dataFields[field] ? `<td>${escapeHTML(item[field])}</td>` : '').join('')}
</tr>
`).join('');
$('#data-table-body').html(rows);
if (SettingsModule.getSettings().dataVisualization) renderChart();
}
function renderChart() {
if (!document.getElementById('data-chart').getContext) return;
const ctx = document.getElementById('data-chart').getContext('2d');
if (dataChartInstance) dataChartInstance.destroy();
const categories = {};
data.forEach(item => { const cat = item.category || '기타'; categories[cat] = (categories[cat] || 0) + 1; });
const chartData = { labels: Object.keys(categories), datasets: [{ label: '카테고리별 데이터 수', data: Object.values(categories), backgroundColor: generateColors(Object.keys(categories).length) }] };
dataChartInstance = new Chart(ctx, { type: 'pie', data: chartData, options: { responsive: true } });
}
function generateColors(count) {
return Array.from({length: count}, (_, i) => `hsl(${i * (360 / count)}, 70%, 50%)`);
}
function escapeHTML(str) {
return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function downloadCSV() {
if (!data.length) {
LoggingModule.log('다운로드할 데이터가 없습니다.', Constants.LOG_LEVELS.WARNING);
return;
}
const headers = Object.keys(Constants.DATA_FIELDS).filter(f => SettingsModule.getSettings().dataFields[f]).map(f => Constants.DATA_FIELDS[f]);
const csv = [headers.join(",")].concat(data.map(item => Object.keys(Constants.DATA_FIELDS).filter(f => SettingsModule.getSettings().dataFields[f]).map(f => `"${escapeCSV(item[f] || '')}"`).join(","))).join("\n");
const link = document.createElement("a");
link.href = `data:text/csv;charset=utf-8,${encodeURIComponent(csv)}`;
link.download = "data.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
LoggingModule.log('CSV 파일이 다운로드되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function downloadJSON() {
if (!data.length) {
LoggingModule.log('다운로드할 데이터가 없습니다.', Constants.LOG_LEVELS.WARNING);
return;
}
const json = JSON.stringify(data, null, 2);
const blob = new Blob([json], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "data.json";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
LoggingModule.log('JSON 파일이 다운로드되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function downloadXML() {
if (!data.length) {
LoggingModule.log('다운로드할 데이터가 없습니다.', Constants.LOG_LEVELS.WARNING);
return;
}
let xml = '<?xml version="1.0" encoding="UTF-8"?><data>';
data.forEach(item => {
xml += '<entry>';
if (SettingsModule.getSettings().dataFields.name) xml += `<name>${escapeXML(item.name || 'No Title')}</name>`;
if (SettingsModule.getSettings().dataFields.url) xml += `<url>${escapeXML(item.url || '')}</url>`;
if (SettingsModule.getSettings().dataFields.description) xml += `<description>${escapeXML(item.description || 'No Description')}</description>`;
if (SettingsModule.getSettings().dataFields.html) xml += `<html><![CDATA[${item.html || ''}]]></html>`;
if (SettingsModule.getSettings().dataFields.category) xml += `<category>${escapeXML(item.category || '')}</category>`;
if (SettingsModule.getSettings().dataFields.quality) xml += `<quality>${escapeXML(item.quality.toString())}</quality>`;
if (SettingsModule.getSettings().dataFields.language) xml += `<language>${escapeXML(item.language)}</language>`;
if (SettingsModule.getSettings().dataFields.wordCount) xml += `<wordCount>${escapeXML(item.wordCount.toString())}</wordCount>`;
if (SettingsModule.getSettings().dataFields.metaTags) xml += `<metaTags>${escapeXML(JSON.stringify(item.metaTags))}</metaTags>`;
if (SettingsModule.getSettings().dataFields.headings) xml += `<headings>${escapeXML(item.headings.join('; '))}</headings>`;
xml += '</entry>';
});
xml += '</data>';
const blob = new Blob([xml], { type: "application/xml" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "data.xml";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
LoggingModule.log('XML 파일이 다운로드되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function downloadXLS() {
if (!data.length) {
LoggingModule.log('다운로드할 데이터가 없습니다.', Constants.LOG_LEVELS.WARNING);
return;
}
const sheet = XLSX.utils.json_to_sheet(data.map(item => {
const entry = {};
if (SettingsModule.getSettings().dataFields.name) entry['사이트 이름'] = item.name;
if (SettingsModule.getSettings().dataFields.url) entry['주소'] = item.url;
if (SettingsModule.getSettings().dataFields.description) entry['설명'] = item.description;
if (SettingsModule.getSettings().dataFields.html) entry['📄 HTML 내용'] = item.html;
if (SettingsModule.getSettings().dataFields.category) entry['분류'] = item.category;
if (SettingsModule.getSettings().dataFields.quality) entry['품질점수'] = item.quality;
if (SettingsModule.getSettings().dataFields.language) entry['언어'] = item.language;
if (SettingsModule.getSettings().dataFields.wordCount) entry['단어 수'] = item.wordCount;
if (SettingsModule.getSettings().dataFields.metaTags) entry['메타 태그'] = JSON.stringify(item.metaTags);
if (SettingsModule.getSettings().dataFields.headings) entry['헤딩'] = item.headings.join('; ');
return entry;
}));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, sheet, "Data");
XLSX.writeFile(wb, "data.xlsx");
LoggingModule.log('XLS 파일이 다운로드되었습니다.', Constants.LOG_LEVELS.SUCCESS);
}
function escapeCSV(str) {
return String(str).replace(/"/g, '""');
}
function escapeXML(str) {
return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function detectCaptcha(doc) {
// CAPTCHA 감지 로직 추가 (예: 특정 클래스나 텍스트 검사)
return !!doc.querySelector('form[action*="captcha"], div.captcha');
}
async function handleCaptcha(url) {
LoggingModule.log(`CAPTCHA 감지됨: ${url}`, Constants.LOG_LEVELS.WARNING);
// CAPTCHA 처리 로직 추가 (예: CAPTCHA 해결을 위한 별도의 서비스 연동 또는 수동 해결 유도)
// 현재는 수동으로 해결하도록 로그만 남김
}
function identifySearchEngine() {
const host = window.location.hostname;
if (host.includes('google.com')) return 'google';
if (host.includes('bing.com')) return 'bing';
if (host.includes('yahoo.com')) return 'yahoo';
if (host.includes('duckduckgo.com')) return 'duckduckgo';
if (host.includes('searx.me')) return 'searx';
// Add other search engines as needed
return null;
}
function getRandomUserAgent() {
const userAgents = SettingsModule.getSettings().userAgents;
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
async function checkRobotsTxt(url) {
try {
const parsed = new URL(url);
const robotsUrl = `${parsed.origin}/robots.txt`;
const res = await fetchWithRetry(robotsUrl, 2, 1000);
return new RobotsParser(res.responseText).isAllowed(url, getRandomUserAgent());
} catch {
LoggingModule.log('robots.txt 확인 실패, 기본 허용.', Constants.LOG_LEVELS.WARNING);
return true;
}
}
async function scheduleCrawling() {
const settings = SettingsModule.getSettings().schedule;
const now = new Date();
const [startHour, startMinute] = settings.startTime.split(':').map(Number);
const startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), startHour, startMinute, 0);
if (startTime < now) startTime.setDate(startTime.getDate() + 1);
const initialDelay = startTime - now;
setTimeout(() => {
startCrawling();
setInterval(startCrawling, settings.interval);
}, initialDelay);
LoggingModule.log(`크롤링 스케줄이 설정되었습니다. 시작 시간: ${startTime.toLocaleString()}, 간격: ${settings.interval / 60000}분`, Constants.LOG_LEVELS.INFO);
}
function getPreviousCrawls() {
return previousCrawls;
}
function updatePreviousCrawlsUI() {
UIModule.updatePreviousCrawlsUI();
}
function escapeHTML(str) {
return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function delay(ms) {
return new Promise(res => setTimeout(res, ms));
}
return {
startCrawling,
stopCrawling,
crawlPage,
processQueue,
handleRequest,
fetchWithRetry,
getProgress,
getCurrentPage,
getTotalPages,
resetData,
clearPreviousCrawls,
finalizeCrawl,
updateDataUI,
renderChart,
downloadCSV,
downloadJSON,
downloadXML,
downloadXLS,
getPreviousCrawls
};
})();
/************* Initialization *************/
function init() {
UIModule.createUI();
CrawlerModule.updateDataUI();
if (SettingsModule.getSettings().dataVisualization) CrawlerModule.renderChart();
if (SettingsModule.getSettings().isCrawling) {
CrawlerModule.startCrawling();
}
}
window.addEventListener('load', init);
/************* Helper Functions *************/
function isValidURL(url) { return CrawlerModule.isValidURL(url); }
function parseCustomKeywords(text) {
const lines = text.split('\n').map(l => l.trim()).filter(l => l);
const ck = {};
lines.forEach(line => {
const [cat, kws] = line.split(':');
if (cat && kws) ck[cat.trim()] = kws.split(',').map(kw => kw.trim()).filter(kw => kw);
});
return ck;
}
function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }
function formatCustomKeywords(ck) {
return Object.entries(ck).map(([cat, kws]) => `${cat}:${kws.join(',')}`).join('\n');
}
// Additional functions or modifications can be added here as needed
})();
이번 개선을 통해 스크립트의 구조가 더욱 명확해졌으며, 사용자 경험과 유지보수성이 크게 향상되었습니다. 필요에 따라 추가적인 기능을 구현하거나, 특정 요구사항에 맞게 조정할 수 있습니다. 사용하시면서 궁금한 점이나 추가적인 요구사항이 있으시면 언제든지 문의해주세요!