// ==UserScript==
// @name Advanced Web Crawler
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 고급 웹 크롤러 스크립트
// @author Your Name
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_download
// @grant GM_xmlhttpRequest
// @connect *
// ==/UserScript==
(function() {
'use strict';
// UI 생성
const createUI = () => {
// 스타일 추가
const style = document.createElement('style');
style.innerHTML = `
#crawler-ui {
position: fixed;
top: 10px;
right: 10px;
width: 400px;
height: 600px;
background: #f9f9f9;
border: 1px solid #ccc;
z-index: 10000;
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
}
#crawler-tabs {
display: flex;
background: #333;
}
.tab {
flex: 1;
padding: 10px;
color: white;
text-align: center;
cursor: pointer;
}
.tab.active {
background: #555;
}
#crawler-content {
flex: 1;
padding: 10px;
overflow: auto;
}
#log, #data, #settings {
display: none;
}
#log.active, #data.active, #settings.active {
display: block;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background: #f2f2f2;
}
.progress-container {
width: 100%;
background: #ddd;
border-radius: 5px;
overflow: hidden;
margin-bottom: 10px;
}
.progress-bar {
width: 0;
height: 20px;
background: #4caf50;
}
.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: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height: 80%;
overflow: auto;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
`;
document.head.appendChild(style);
// UI 구조
const ui = document.createElement('div');
ui.id = 'crawler-ui';
ui.innerHTML = `
<div id="crawler-tabs">
<div class="tab active" data-tab="log">📜 로그</div>
<div class="tab" data-tab="data">📊 데이터</div>
<div class="tab" data-tab="settings">⚙️ 설정</div>
</div>
<div id="crawler-content">
<div id="log" class="active">
<textarea id="log-area" style="width:100%; height:100%;"></textarea>
</div>
<div id="data">
<table>
<thead>
<tr>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>분류</th>
<th>콘텐츠 품질</th>
</tr>
</thead>
<tbody id="data-body">
</tbody>
</table>
</div>
<div id="settings">
<label>크롤링 속도 (초): <input type="number" id="crawl-delay" value="3"></label><br>
<label>블랙리스트 도메인 (콤마로 구분): <input type="text" id="blacklist-domains"></label><br>
<label>화이트리스트 도메인 (콤마로 구분): <input type="text" id="whitelist-domains"></label><br>
<button id="save-settings">저장</button>
</div>
</div>
<div class="progress-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
<button id="start-crawl" title="크롤링 시작">시작</button>
<button id="stop-crawl" title="크롤링 중지">중지</button>
<button id="reset-crawl" title="크롤링 초기화">초기화</button>
<button id="download-csv" title="CSV 다운로드">CSV</button>
<button id="download-json" title="JSON 다운로드">JSON</button>
`;
document.body.appendChild(ui);
// 모달 생성
const modal = document.createElement('div');
modal.className = 'modal';
modal.innerHTML = `
<div class="modal-content">
<span class="close">×</span>
<pre id="modal-html"></pre>
</div>
`;
document.body.appendChild(modal);
// 탭 이벤트
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const tabName = tab.getAttribute('data-tab');
document.querySelectorAll('#crawler-content > div').forEach(content => {
content.classList.remove('active');
});
document.getElementById(tabName).classList.add('active');
});
});
// 저장 버튼 이벤트
document.getElementById('save-settings').addEventListener('click', () => {
const delay = parseInt(document.getElementById('crawl-delay').value);
const blacklist = document.getElementById('blacklist-domains').value.split(',').map(s => s.trim());
const whitelist = document.getElementById('whitelist-domains').value.split(',').map(s => s.trim());
GM_setValue('crawlDelay', delay);
GM_setValue('blacklist', blacklist);
GM_setValue('whitelist', whitelist);
log('설정이 저장되었습니다.');
});
// 버튼 이벤트
document.getElementById('start-crawl').addEventListener('click', startCrawling);
document.getElementById('stop-crawl').addEventListener('click', stopCrawling);
document.getElementById('reset-crawl').addEventListener('click', resetCrawling);
document.getElementById('download-csv').addEventListener('click', downloadCSV);
document.getElementById('download-json').addEventListener('click', downloadJSON);
// 로그 모달 이벤트
modal.querySelector('.close').addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (e) => {
if (e.target == modal) {
modal.style.display = 'none';
}
});
// HTML 내용 모달 표시
document.getElementById('data-body').addEventListener('click', (e) => {
if (e.target && e.target.nodeName === 'TD' && e.target.dataset.html) {
document.getElementById('modal-html').innerText = e.target.dataset.html;
modal.style.display = 'block';
}
});
};
// 로깅 함수
const log = (message) => {
const logArea = document.getElementById('log-area');
logArea.value += `[${new Date().toLocaleTimeString()}] ${message}\n`;
logArea.scrollTop = logArea.scrollHeight;
};
// 크롤링 제어 변수
let crawling = false;
let currentPage = 1;
let currentSite = 0;
let results = [];
let totalPages = 1;
let totalSites = 0;
// 크롤링 시작
const startCrawling = () => {
if (crawling) {
log('이미 크롤링이 진행 중입니다.');
return;
}
crawling = true;
currentPage = 1;
currentSite = 0;
results = [];
document.getElementById('data-body').innerHTML = '';
log('크롤링을 시작합니다.');
crawlPage();
};
// 크롤링 중지
const stopCrawling = () => {
if (!crawling) {
log('크롤링이 진행 중이지 않습니다.');
return;
}
crawling = false;
log('크롤링이 중지되었습니다.');
};
// 크롤링 초기화
const resetCrawling = () => {
crawling = false;
currentPage = 1;
currentSite = 0;
results = [];
document.getElementById('data-body').innerHTML = '';
log('크롤링이 초기화되었습니다.');
};
// 크롤링 함수
const crawlPage = () => {
if (!crawling) return;
log(`페이지 ${currentPage}을 크롤링 중입니다.`);
// 예시: 검색 결과 페이지에서 사이트 목록을 가져오는 로직
// 실제 웹사이트 구조에 맞게 수정 필요
const sites = Array.from(document.querySelectorAll('a.result-link')).map(a => ({
name: a.textContent.trim(),
url: a.href,
description: a.parentElement.querySelector('.description')?.textContent.trim() || ''
}));
totalSites = sites.length;
totalPages = parseInt(document.querySelector('.pagination .total-pages')?.textContent) || 1;
processSites(sites);
};
// 사이트 처리
const processSites = async (sites) => {
for (; currentSite < sites.length; currentSite++) {
if (!crawling) break;
const site = sites[currentSite];
if (isBlacklisted(site.url) || !isWhitelisted(site.url)) {
log(`블랙리스트/화이트리스트에 의해 제외된 사이트: ${site.url}`);
continue;
}
await fetchSiteData(site);
updateProgress();
await delay(GM_getValue('crawlDelay', 3) * 1000);
}
if (currentPage < totalPages && crawling) {
currentPage++;
crawlNextPage();
} else {
crawling = false;
log('크롤링이 완료되었습니다.');
}
};
// 다음 페이지로 이동
const crawlNextPage = () => {
window.scrollTo(0, 0);
// 다음 페이지 버튼 클릭 로직
const nextBtn = document.querySelector('.pagination .next');
if (nextBtn) {
nextBtn.click();
setTimeout(crawlPage, 2000);
} else {
crawling = false;
log('더 이상 페이지가 없습니다.');
}
};
// 사이트 데이터 가져오기
const fetchSiteData = (site) => {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: site.url,
onload: function(response) {
if (response.status === 200) {
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const htmlContent = response.responseText;
const textContent = doc.body.innerText;
const quality = evaluateContentQuality(textContent);
const category = classifyKeywords(site.description);
results.push({ ...site, htmlContent, textContent, quality, category });
addDataToTable({ ...site, htmlContent, textContent, quality, category });
resolve();
} else {
log(`에러 ${response.status}: ${site.url}`);
resolve();
}
},
onerror: function(err) {
log(`요청 실패: ${site.url}`);
resolve();
}
});
});
};
// 데이터 테이블에 추가
const addDataToTable = (data) => {
const tbody = document.getElementById('data-body');
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${data.name}</td>
<td><a href="${data.url}" target="_blank">${data.url}</a></td>
<td>${data.description}</td>
<td>${data.category}</td>
<td>${data.quality}</td>
`;
tr.querySelectorAll('td')[1].dataset.html = data.htmlContent;
tbody.appendChild(tr);
};
// 진행률 업데이트
const updateProgress = () => {
const progressBar = document.getElementById('progress-bar');
const total = totalPages * totalSites;
const current = results.length;
const percent = Math.min((current / total) * 100, 100);
progressBar.style.width = percent + '%';
};
// 지연 함수
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 콘텐츠 품질 평가
const evaluateContentQuality = (text) => {
const wordCount = text.split(/\s+/).length;
return wordCount > 100 ? '높음' : '낮음';
};
// 키워드 분류
const classifyKeywords = (description) => {
const keywords = ['교육', '뉴스', '블로그', '쇼핑'];
for (let kw of keywords) {
if (description.includes(kw)) return kw;
}
return '기타';
};
// 블랙리스트 검사
const isBlacklisted = (url) => {
const blacklist = GM_getValue('blacklist', []);
return blacklist.some(domain => url.includes(domain));
};
// 화이트리스트 검사
const isWhitelisted = (url) => {
const whitelist = GM_getValue('whitelist', []);
if (whitelist.length === 0) return true;
return whitelist.some(domain => url.includes(domain));
};
// CSV 다운로드
const downloadCSV = () => {
const headers = ['사이트 이름', '주소', '설명', '분류', '콘텐츠 품질'];
const rows = results.map(r => [r.name, r.url, r.description, r.category, r.quality]);
let csv = headers.join(',') + '\n';
rows.forEach(row => {
csv += row.map(item => `"${item}"`).join(',') + '\n';
});
GM_download({
url: 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv),
name: 'data.csv',
saveAs: true
});
};
// JSON 다운로드
const downloadJSON = () => {
const json = JSON.stringify(results, null, 2);
GM_download({
url: 'data:application/json;charset=utf-8,' + encodeURIComponent(json),
name: 'data.json',
saveAs: true
});
};
// 키보드 단축키
const setupShortcuts = () => {
document.addEventListener('keydown', (e) => {
if (e.ctrlKey) {
switch(e.key) {
case 's':
e.preventDefault();
document.getElementById('save-settings').click();
break;
case 'p':
e.preventDefault();
startCrawling();
break;
case 'q':
e.preventDefault();
stopCrawling();
break;
case 'd':
e.preventDefault();
downloadCSV();
break;
case 'j':
e.preventDefault();
downloadJSON();
break;
case '1':
e.preventDefault();
activateTab('log');
break;
case '2':
e.preventDefault();
activateTab('data');
break;
case '3':
e.preventDefault();
activateTab('settings');
break;
}
}
});
};
const activateTab = (tabName) => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelector(`.tab[data-tab="${tabName}"]`).classList.add('active');
document.querySelectorAll('#crawler-content > div').forEach(content => {
content.classList.remove('active');
});
document.getElementById(tabName).classList.add('active');
};
// 실시간 데이터 필터링
const setupSearchFilter = () => {
const searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.placeholder = '검색...';
searchInput.style.width = '100%';
searchInput.addEventListener('input', () => {
filterTable(searchInput.value);
});
document.getElementById('data').prepend(searchInput);
};
const filterTable = (keyword) => {
const rows = document.querySelectorAll('#data-body tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
let match = false;
cells.forEach(cell => {
if (cell.textContent.toLowerCase().includes(keyword.toLowerCase())) {
match = true;
}
});
row.style.display = match ? '' : 'none';
});
};
// 초기화
const init = () => {
createUI();
setupShortcuts();
setupSearchFilter();
log('크롤러가 초기화되었습니다.');
};
window.addEventListener('load', init);
})();