if (!isValidSettings) {
$('#error-message').text('설정값이 유효하지 않습니다. 올바른 값을 입력하세요.').show();
setTimeout(() => { $('#error-message').fadeOut(); }, 5000);
return;
}
settings.delay = delay;
settings.delayRandom = delayRandom;
settings.maxPages = maxPages;
const selectedUA = parseInt($('#user-agent-select').val(), 10);
settings.userAgentIndex = isNaN(selectedUA) ? 0 : selectedUA;
settings.contentTypes.include = $('#content-include-input').val().split(',').map(ct => ct.trim()).filter(ct => ct) || defaultSettings.contentTypes.include;
settings.contentTypes.exclude = $('#content-exclude-input').val().split(',').map(ct => ct.trim()).filter(ct => ct) || defaultSettings.contentTypes.exclude;
settings.timeout = timeout;
settings.includeKeywords = $('#include-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw) || defaultSettings.includeKeywords;
settings.excludeKeywords = $('#exclude-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw) || defaultSettings.excludeKeywords;
settings.regexInclude = $('#regex-include-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx) || defaultSettings.regexInclude;
settings.regexExclude = $('#regex-exclude-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx) || defaultSettings.regexExclude;
settings.language = $('#language-select').val() || [];
settings.minWordCount = minWordCount;
settings.maxWordCount = maxWordCount;
settings.maxDepth = maxDepth;
settings.proxy = $('#proxy-input').val().trim() || defaultSettings.proxy;
['name','url','description','html','category','quality','language','wordCount','metaTags','headings'].forEach(field => {
settings.dataFields[field] = $(`#field-${field}`).is(':checked');
});
settings.retryAttempts = retryAttempts;
settings.retryDelay = retryDelay;
settings.schedule.enabled = $('#schedule-enabled').is(':checked');
settings.schedule.startTime = $('#start-time-input').val() || defaultSettings.schedule.startTime;
settings.schedule.interval = settings.schedule.enabled ? (isNaN(interval) ? defaultSettings.schedule.interval : interval) : defaultSettings.schedule.interval;
Object.keys(settings.searchEngines).forEach(engine => { settings.searchEngines[engine] = $(`#engine-${engine}`).is(':checked'); });
settings.blacklist = $('#blacklist-input').val().split('\n').map(d => d.trim()).filter(d => d) || defaultSettings.blacklist;
settings.whitelist = $('#whitelist-input').val().split('\n').map(d => d.trim()).filter(d => d) || defaultSettings.whitelist;
settings.respectRobots = $('#respect-robots-checkbox').is(':checked');
settings.maxConcurrentRequests = parseInt($('#max-concurrent-requests-input').val(), 10) || defaultSettings.maxConcurrentRequests;
settings.dataVisualization = $('#data-visualization-checkbox').is(':checked');
settings.exportFormats.csv = $('#export-csv').is(':checked');
settings.exportFormats.json = $('#export-json').is(':checked');
settings.exportFormats.xml = $('#export-xml').is(':checked');
settings.exportFormats.xls = $('#export-xls').is(':checked');
settings.advancedLogging = $('#advanced-logging-checkbox').is(':checked');
settings.enableCaptchas = $('#enable-captchas-checkbox').is(':checked');
const customKeywords = parseCustomKeywords($('#custom-keywords-input').val());
settings.customKeywords = customKeywords;
// Save Settings
GM_setValue('delay', settings.delay);
GM_setValue('delayRandom', settings.delayRandom);
GM_setValue('maxPages', settings.maxPages);
GM_setValue('userAgentIndex', settings.userAgentIndex);
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('retryAttempts', settings.retryAttempts);
GM_setValue('retryDelay', settings.retryDelay);
GM_setValue('schedule', settings.schedule);
GM_setValue('searchEngines', settings.searchEngines);
GM_setValue('blacklist', settings.blacklist);
GM_setValue('whitelist', settings.whitelist);
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);
totalPages = settings.maxPages;
GM_setValue('totalPages', totalPages);
log('설정이 저장되었습니다.', 'success');
if (settings.schedule.enabled) {
scheduleCrawling();
}
updateDataUI();
if (settings.dataVisualization) renderChart();
}
function resetSettings() {
if (confirm("기본 설정으로 초기화하시겠습니까?")) {
Object.keys(defaultSettings).forEach(key => GM_deleteValue(key));
Object.assign(settings, defaultSettings);
['userAgents','userAgentIndex','contentTypes','dataFields','exportFormats','advancedLogging','enableCaptchas'].forEach(key => GM_setValue(key, settings[key]));
GM_setValue('customKeywords', {});
GM_setValue('logs', []);
GM_setValue('data', []);
GM_setValue('visitedUrls', []);
GM_setValue('previousCrawls', []);
$('#custom-keywords-input').val('');
updateUserAgentSelect();
updateDataUI();
updateLogsUI();
$('#previous-crawls-body').empty();
if (settings.dataVisualization) renderChart();
log('기본 설정으로 초기화되었습니다.', 'success');
}
}
async function startCrawling() {
if (isCrawling) { log('이미 크롤링이 진행 중입니다.', 'warning'); return; }
if (!Object.values(settings.searchEngines).some(v => v)) { log('사용할 검색 엔진이 하나도 선택되지 않았습니다.', 'error'); return; }
isCrawling = true;
GM_setValue('isCrawling', isCrawling);
log('크롤링을 시작합니다.', 'info');
setButtonStates();
currentPage = parseInt(GM_getValue('currentPage', 1), 10);
totalPages = parseInt(GM_getValue('totalPages', settings.maxPages), 10);
GM_setValue('totalPages', totalPages);
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', previousCrawls);
updatePreviousCrawlsUI();
}
await crawlPage(currentDepth);
}
function stopCrawling() {
if (!isCrawling) { log('크롤링이 진행 중이지 않습니다.', 'warning'); return; }
isCrawling = false;
GM_setValue('isCrawling', isCrawling);
log('크롤링이 중지되었습니다.', 'warning');
finalizeCrawl('중지됨');
setButtonStates();
}
function setButtonStates() {
$('#start-crawling').prop('disabled', isCrawling);
$('#stop-crawling').prop('disabled', !isCrawling);
}
async function crawlPage(depth) {
try {
while (isCrawling && currentPage <= totalPages && depth <= settings.maxDepth) {
log(`페이지 ${currentPage} 크롤링 시작. (깊이: ${depth})`, 'info');
if (settings.respectRobots && !(await checkRobotsTxt(window.location.href))) {
log(`robots.txt에 의해 크롤링이 금지된 페이지: ${window.location.href}`, 'warning');
break;
}
const searchEngine = identifySearchEngine();
if (!searchEngine || !searchEngineHandlers[searchEngine]) {
log(`지원되지 않는 검색 엔진: ${window.location.hostname}`, 'error');
break;
}
const doc = document;
const handler = searchEngineHandlers[searchEngine];
const results = handler.extractResults(doc);
if (!results) { log('검색 결과를 찾을 수 없습니다.', 'error'); break; }
results.forEach(result => {
if (!isCrawling) return;
const { name, url, description } = result;
if (visitedUrls.has(url) || !isValidURL(url) ||
(settings.whitelist.length && !settings.whitelist.some(d => url.includes(d))) ||
settings.blacklist.some(d => url.includes(d)) ||
(settings.includeKeywords.length && !settings.includeKeywords.some(k => url.includes(k) || description.includes(k))) ||
(settings.excludeKeywords.some(k => url.includes(k) || description.includes(k))) ||
(settings.regexInclude.length && !settings.regexInclude.some(r => new RegExp(r).test(url) || new RegExp(r).test(description))) ||
(settings.regexExclude.length && settings.regexExclude.some(r => new RegExp(r).test(url) || new RegExp(r).test(description)))) {
return;
}
requestQueue.push({ url, depth });
if (activeRequests >= settings.maxConcurrentRequests) return;
});
if (previousCrawls.length && previousCrawls[previousCrawls.length -1].status === '진행 중') {
previousCrawls[previousCrawls.length -1].count += results.length;
GM_setValue('previousCrawls', previousCrawls);
updatePreviousCrawlsUI();
}
await processQueue();
progress = (currentPage / totalPages) * 100;
GM_setValue('progress', progress);
updateLogsUI();
if (currentPage < totalPages && isCrawling) {
const nextUrl = handler.getNextPageUrl(doc);
if (nextUrl) {
currentPage++;
GM_setValue('currentPage', currentPage);
depth++;
GM_setValue('currentDepth', depth);
log(`다음 페이지로 이동: ${currentPage}`, 'info');
await dynamicDelay();
const nextPageContent = await fetchPageContent(nextUrl);
if (nextPageContent) {
updatePageContent(nextPageContent);
continue;
} else {
log('다음 페이지 내용을 가져올 수 없습니다.', 'error');
break;
}
} else { log('다음 페이지 링크를 찾을 수 없습니다.', 'error'); break; }
} else { break; }
}
if (isCrawling && currentPage > totalPages && activeRequests === 0 && requestQueue.length === 0) {
log('크롤링이 완료되었습니다.', 'success');
finalizeCrawl('완료됨');
isCrawling = false;
GM_setValue('isCrawling', isCrawling);
setButtonStates();
GM_setValue('progress', 100);
$('.progress-bar-fill').css('width', `100%`);
$('.status-text').text(`진행률: 100% (${currentPage}/${totalPages} 페이지)`);
}
} catch (error) {
log(`크롤링 중 오류 발생: ${error.message}`, 'error');
finalizeCrawl('오류 발생');
}
}
async function processQueue() {
while (requestQueue.length && activeRequests < settings.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, settings.retryAttempts, settings.retryDelay);
const contentType = getContentType(response);
if (!isContentTypeAllowed(contentType)) { log(`허용되지 않은 콘텐츠 유형(${contentType})의 URL: ${url}`, 'warning'); return; }
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const text = doc.body ? doc.body.innerText : '';
if (settings.enableCaptchas && detectCaptcha(doc)) { await handleCaptcha(url); return; }
const wc = text.split(/\s+/).length;
if (wc < settings.minWordCount || wc > settings.maxWordCount) {
log(`단어 수 조건에 맞지 않는 URL: ${url} (${wc} 단어)`, '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: wc, category };
if (settings.dataFields.name) entry.name = extractName(doc) || 'No Title';
if (settings.dataFields.description) entry.description = extractDescription(doc) || 'No Description';
if (settings.dataFields.html) entry.html = response.responseText;
if (settings.dataFields.metaTags) entry.metaTags = meta;
if (settings.dataFields.headings) entry.headings = headings;
data.push(entry);
GM_setValue('data', JSON.stringify([...data]));
updateDataUI();
log(`데이터 수집 완료: ${url}`, 'success');
if (settings.dataVisualization) renderChart();
}
if (depth < settings.maxDepth) {
const links = extractLinks(doc);
links.forEach(link => { if (!visitedUrls.has(link) && isValidURL(link)) requestQueue.push({ url: link, depth: depth + 1 }); });
}
} catch (error) {
log(`데이터 수집 실패: ${url} - ${error.message}`, '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) { log(`요청 실패 (${i}/${attempts}): ${url} - ${e.message}`, 'warning'); if (i < attempts) await delay(delayMs); }
}
throw new Error('모든 재시도 시도가 실패했습니다.');
}
function isAnySearchEngineEnabled() { return Object.values(settings.searchEngines).some(v => v); }
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 extractSearchResults() {
// Deprecated: Using handlers now
}
function getNextPageUrl() {
// Deprecated: Using handlers now
}
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';
// Add other search engines as needed
return null;
}
function GM_xmlhttpRequestPromise(url) {
return new Promise((resolve, reject) => {
let reqUrl = settings.proxy ? `${settings.proxy}?url=${encodeURIComponent(url)}` : url;
GM_xmlhttpRequest({
method: "GET",
url: reqUrl,
headers: { 'User-Agent': getCurrentUserAgent(), 'Accept': '*/*' },
timeout: settings.timeout,
onload: res => (res.status >= 200 && res.status < 300) ? resolve(res) : reject(new Error(`HTTP ${res.status}`)),
onerror: () => reject(new Error('Request failed')),
ontimeout: () => reject(new Error('Request timed out'))
});
});
}
function getCurrentUserAgent() { return settings.userAgents[settings.userAgentIndex % settings.userAgents.length]; }
function getContentType(res) { return res.responseHeaders.split('\n').find(h => h.toLowerCase().startsWith('content-type'))?.split(':')[1].trim().split(';')[0] || ''; }
function isContentTypeAllowed(ct) {
if (settings.contentTypes.include.length && !settings.contentTypes.include.includes(ct)) return false;
if (settings.contentTypes.exclude.includes(ct)) return false;
return true;
}
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 isValidURL(url) { try { new URL(url); return true; } catch { return false; } }
async function checkRobotsTxt(url) {
try {
const parsed = new URL(url);
const robots = `${parsed.origin}/robots.txt`;
const res = await GM_xmlhttpRequestPromise(robots);
return new RobotsParser(robots, res.responseText).isAllowed(url, getCurrentUserAgent());
} catch {
log('robots.txt 확인 실패, 기본 허용.', 'warning');
return true;
}
}
class RobotsParser {
constructor(url, 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;
}
}
function delay(ms) { return new Promise(res => setTimeout(res, ms)); }
function formatCustomKeywords(ck) { return Object.entries(ck).map(([c, kws]) => `${c}:${kws.join(',')}`).join('\n'); }
function getFieldName(field) { return { name: '사이트 이름', url: '주소', description: '설명', html: '📄 HTML 내용', category: '분류', quality: '품질점수', language: '언어', wordCount: '단어 수', metaTags: '메타 태그', headings: '헤딩' }[field]; }
function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }
async function handleCaptcha(url) {
log(`CAPTCHA 감지됨: ${url}`, 'warning');
// CAPTCHA 처리 로직 추가 (제한적)
// 예: CAPTCHA 해결을 위한 별도의 서비스 연동 또는 수동 해결 유도
}
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 escapeXML(str) { return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); }
async function scheduleCrawling() {
const now = new Date();
const [startHour, startMinute] = settings.schedule.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.schedule.interval);
}, initialDelay);
log(`크롤링 스케줄이 설정되었습니다. 시작 시간: ${startTime.toLocaleString()}, 간격: ${settings.schedule.interval / 60000}분`, 'info');
}
function finalizeCrawl(status) {
if (previousCrawls.length) {
previousCrawls[previousCrawls.length -1].status = status;
GM_setValue('previousCrawls', previousCrawls);
updatePreviousCrawlsUI();
}
}
function updatePreviousCrawlsUI() {
$('#previous-crawls-body').html(previousCrawls.map(crawl => `
<tr>
<td>${crawl.date}</td>
<td>${crawl.count}</td>
<td>${crawl.status}</td>
</tr>
`).join(''));
}
function init() {
createUI();
if (isCrawling) {
log('크롤링 재개됨.', 'info');
setButtonStates();
crawlPage(currentDepth);
}
else log('크롤러 초기화됨.', 'info');
}
window.addEventListener('load', init);
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;
}
}
async function startCrawling() {
if (isCrawling) {
log('이미 크롤링이 진행 중입니다.', 'warning');
return;
}
if (!Object.values(settings.searchEngines).some(v => v)) {
log('사용할 검색 엔진이 하나도 선택되지 않았습니다.', 'error');
return;
}
isCrawling = true;
GM_setValue('isCrawling', isCrawling);
log('크롤링을 시작합니다.', 'info');
setButtonStates();
currentPage = parseInt(GM_getValue('currentPage', 1), 10);
totalPages = parseInt(GM_getValue('totalPages', settings.maxPages), 10);
GM_setValue('totalPages', totalPages);
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', previousCrawls);
updatePreviousCrawlsUI();
}
await crawlPage(currentDepth);
}
// Add additional functions or modifications as needed
})(); 크롬에서 쓰는 다크모드나 다양한 테마들을 추가해서 사용자들의 눈을 보호해!
다크 모드 및 다양한 테마를 추가하여 사용자의 눈을 보호하는 기능을 구현하는 것은 훌륭한 개선 사항입니다. 이를 위해 사용자 인터페이스(UI)에 테마 전환 버튼을 추가하고, CSS를 수정하여 여러 테마(예: 라이트 모드, 다크 모드)를 지원하도록 합니다. 아래는 귀하의 기존 스크립트에 다크 모드와 테마 전환 기능을 추가한 업데이트된 전체 스크립트입니다.
주요 변경 사항:
CSS 업데이트: 라이트 모드와 다크 모드를 지원하기 위해 CSS를 수정하고, 테마 전환을 원활하게 하기 위해 CSS 변수를 도입했습니다.
테마 전환 버튼 추가: UI에 테마를 변경할 수 있는 버튼을 추가했습니다.
테마 저장 및 적용: 선택한 테마를 GM_setValue와 GM_getValue를 사용하여 저장하고, 페이지 로드 시 해당 테마를 적용하도록 했습니다.