// ==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
// @require https://code.jquery.com/jquery-3.6.0.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
// @connect *
// ==/UserScript==
(function() {
'use strict';
// 기본 설정
let isCrawling = false;
let currentPage = 1;
let totalPages = 10; // 예시
let data = [];
let visited = new Set();
let blacklist = new Set(GM_getValue('blacklist', []));
let whitelist = new Set(GM_getValue('whitelist', []));
// UI 생성
const ui = $(`
<div id="crawler-ui" style="position: fixed; top: 10px; left: 10px; width: 400px; height: 600px; background: white; border: 2px solid #000; z-index: 10000; overflow: hidden;">
<div style="display: flex; border-bottom: 1px solid #000;">
<div class="tab" data-tab="logs" style="flex: 1; padding: 10px; cursor: pointer; background: #ccc;">📜 로그</div>
<div class="tab" data-tab="data" style="flex: 1; padding: 10px; cursor: pointer; background: #eee;">📊 데이터</div>
<div class="tab" data-tab="settings" style="flex: 1; padding: 10px; cursor: pointer; background: #eee;">⚙️ 설정</div>
</div>
<div id="tab-logs" style="display: block; padding: 10px; height: 550px; overflow-y: scroll;">
<textarea id="log-output" style="width: 100%; height: 100%;"></textarea>
</div>
<div id="tab-data" style="display: none; padding: 10px; height: 550px; overflow-y: scroll;">
<table id="data-table" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>HTML</th>
<th>텍스트</th>
<th>분류</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="tab-settings" style="display: none; padding: 10px; height: 550px; overflow-y: scroll;">
<div>
<label>블랙리스트 도메인 (콤마로 구분)</label>
<input type="text" id="blacklist-input" style="width: 100%;" value="${Array.from(blacklist).join(',')}">
</div>
<div>
<label>화이트리스트 도메인 (콤마로 구분)</label>
<input type="text" id="whitelist-input" style="width: 100%;" value="${Array.from(whitelist).join(',')}">
</div>
<button id="save-settings">저장</button>
</div>
<div style="position: absolute; bottom: 10px; left: 10px; right: 10px;">
<button id="start-btn">시작</button>
<button id="stop-btn">중지</button>
<button id="reset-btn">초기화</button>
<div id="progress-bar" style="width: 100%; background: #ddd; height: 20px; margin-top: 10px;">
<div id="progress" style="width: 0%; background: #4caf50; height: 100%;"></div>
</div>
<span id="progress-percent">0%</span>
</div>
</div>
`);
$('body').append(ui);
// 탭 전환
$('.tab').on('click', function() {
const tab = $(this).data('tab');
$('.tab').css('background', '#eee');
$(this).css('background', '#ccc');
$('#tab-logs, #tab-data, #tab-settings').hide();
$(`#tab-${tab}`).show();
});
// 설정 저장
$('#save-settings').on('click', function() {
const bl = $('#blacklist-input').val().split(',').map(s => s.trim()).filter(s => s);
const wl = $('#whitelist-input').val().split(',').map(s => s.trim()).filter(s => s);
GM_setValue('blacklist', bl);
GM_setValue('whitelist', wl);
blacklist = new Set(bl);
whitelist = new Set(wl);
log('설정이 저장되었습니다.');
});
// 로그 함수
function log(message) {
$('#log-output').val($('#log-output').val() + message + '\n');
}
// 데이터 추가 함수
function addData(site) {
data.push(site);
const row = `<tr>
<td>${site.name}</td>
<td><a href="${site.url}" target="_blank">${site.url}</a></td>
<td>${site.description}</td>
<td><button class="view-html" data-html="${encodeURIComponent(site.html)}">보기</button></td>
<td>${site.text}</td>
<td>${site.category}</td>
</tr>`;
$('#data-table tbody').append(row);
}
// HTML 보기 모달
$(document).on('click', '.view-html', function() {
const htmlContent = decodeURIComponent($(this).data('html'));
const modal = $(`
<div id="html-modal" style="position: fixed; top: 10%; left: 10%; width: 80%; height: 80%; background: white; border: 2px solid #000; z-index: 10001; overflow: auto;">
<div style="text-align: right;"><button id="close-modal">닫기</button></div>
<pre>${htmlContent}</pre>
</div>
`);
$('body').append(modal);
});
$(document).on('click', '#close-modal', function() {
$('#html-modal').remove();
});
// 크롤링 시작
$('#start-btn').on('click', function() {
if (isCrawling) {
log('이미 크롤링 중입니다.');
return;
}
isCrawling = true;
log('크롤링을 시작합니다.');
crawlPage(currentPage);
});
// 크롤링 중지
$('#stop-btn').on('click', function() {
if (!isCrawling) {
log('현재 크롤링 중이 아닙니다.');
return;
}
isCrawling = false;
log('크롤링을 중지합니다.');
});
// 크롤링 초기화
$('#reset-btn').on('click', function() {
isCrawling = false;
currentPage = 1;
data = [];
visited.clear();
$('#data-table tbody').empty();
$('#log-output').val('');
$('#progress').css('width', '0%');
$('#progress-percent').text('0%');
log('크롤링이 초기화되었습니다.');
});
// 크롤링 함수
async function crawlPage(page) {
if (!isCrawling || page > totalPages) {
isCrawling = false;
log('크롤링이 완료되었습니다.');
return;
}
log(`페이지 ${page} 크롤링 중...`);
// 예시: 검색 URL 구성
const searchUrl = `https://example.com/search?page=${page}`;
try {
const response = await fetch(searchUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const results = doc.querySelectorAll('.result'); // 예시 셀렉터
for (let result of results) {
const name = result.querySelector('.name').innerText;
const url = result.querySelector('.url').href;
const description = result.querySelector('.description').innerText;
if ((whitelist.size > 0 && !whitelist.has(new URL(url).hostname)) || blacklist.has(new URL(url).hostname)) {
log(`건너뜀: ${url}`);
continue;
}
if (visited.has(url)) {
log(`중복 방문: ${url}`);
continue;
}
visited.add(url);
const siteHtml = await fetch(url).then(res => res.text());
const siteText = new DOMParser().parseFromString(siteHtml, 'text/html').body.innerText;
const category = classifyKeywords(description);
addData({name, url, description, html: siteHtml, text: siteText, category});
log(`수집 완료: ${url}`);
updateProgress();
await delay(3000);
}
currentPage++;
crawlPage(currentPage);
} catch (error) {
log(`에러 발생: ${error}`);
crawlPage(page);
}
}
// 지연 함수
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 진행률 업데이트
function updateProgress() {
const percent = Math.min((currentPage / totalPages) * 100, 100);
$('#progress').css('width', `${percent}%`);
$('#progress-percent').text(`${percent}%`);
}
// 키워드 분류 함수
function classifyKeywords(description) {
const keywords = ['education', 'technology', 'news']; // 예시 키워드
for (let kw of keywords) {
if (description.toLowerCase().includes(kw)) {
return kw;
}
}
return '기타';
}
// 단축키 설정
$(document).on('keydown', function(e) {
if (e.ctrlKey && e.key === '1') {
$('.tab').css('background', '#eee');
$('.tab[data-tab="logs"]').css('background', '#ccc');
$('#tab-logs, #tab-data, #tab-settings').hide();
$('#tab-logs').show();
e.preventDefault();
}
if (e.ctrlKey && e.key === '2') {
$('.tab').css('background', '#eee');
$('.tab[data-tab="data"]').css('background', '#ccc');
$('#tab-logs, #tab-data, #tab-settings').hide();
$('#tab-data').show();
e.preventDefault();
}
if (e.ctrlKey && e.key === '3') {
$('.tab').css('background', '#eee');
$('.tab[data-tab="settings"]').css('background', '#ccc');
$('#tab-logs, #tab-data, #tab-settings').hide();
$('#tab-settings').show();
e.preventDefault();
}
if (e.ctrlKey && e.key === 's') {
$('#save-settings').click();
e.preventDefault();
}
if (e.ctrlKey && e.key === 'p') {
$('#start-btn').click();
e.preventDefault();
}
if (e.ctrlKey && e.key === 'q') {
$('#stop-btn').click();
e.preventDefault();
}
if (e.ctrlKey && e.key === 'd') {
downloadCSV();
e.preventDefault();
}
if (e.ctrlKey && e.key === 'j') {
downloadJSON();
e.preventDefault();
}
});
// CSV 다운로드
function downloadCSV() {
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
const wbout = XLSX.write(wb, {bookType:'csv', type:'array'});
const blob = new Blob([wbout], {type: "text/csv;charset=utf-8;"});
saveAs(blob, "data.csv");
log('CSV 파일이 다운로드되었습니다.');
}
// JSON 다운로드
function downloadJSON() {
const blob = new Blob([JSON.stringify(data, null, 2)], {type: "application/json"});
saveAs(blob, "data.json");
log('JSON 파일이 다운로드되었습니다.');
}
// 자동 새로고침 시 초기화
window.addEventListener('beforeunload', function () {
GM_setValue('crawling_state', 'initialized');
});
// 진행률 바 상세화
// 추가적인 진행률 정보 표시 가능
// 사이트 정보 캡쳐
async function captureSite(url) {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.appendChild(iframe);
await delay(5000); // 로드 대기
const canvas = await html2canvas(iframe.contentDocument.body);
const imgData = canvas.toDataURL('image/png');
GM_download(imgData, `screenshot_${Date.now()}.png`);
document.body.removeChild(iframe);
}
// 사이트 전체 정보 가져오기
// 이미 HTML과 텍스트를 수집하고 있음
// 광고 제외 기능 강화
// 예시: 특정 광고 관련 키워드 필터링
function isAdSite(description) {
const adKeywords = ['advertisement', 'sponsor'];
return adKeywords.some(kw => description.toLowerCase().includes(kw));
}
// 데이터 테이블 검색 필터
$('#data-table').before('<input type="text" id="search-input" placeholder="검색...">');
$('#search-input').on('input', function() {
const keyword = $(this).val().toLowerCase();
$('#data-table tbody tr').each(function() {
const row = $(this);
const text = row.text().toLowerCase();
row.toggle(text.includes(keyword));
});
});
})();