안녕하세요! 요청하신 Tampermonkey 스크립트를 최대한 상세하게 작성해 보았습니다. 이 스크립트는 웹 크롤링을 수행하며, 다양한 기능을 포함하고 있습니다. 다만, Tampermonkey를 이용한 대규모 크롤링은 브라우저의 제한사항과 보안 정책 때문에 일부 기능 구현이 어려울 수 있습니다. 교육적인 목적으로 사용하신다면 충분히 유용할 것으로 생각됩니다. 아래는 요청하신 기능을 구현한 Tampermonkey 스크립트입니다.
javascript Copy code
// ==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
// @license MIT
// ==/UserScript==
(function() {
'use strict';
// ============================
// 기본 설정
// ============================
const settings = {
crawlDelay: 3000, // 밀리초 단위
maxPages: 100,
blacklist: [],
whitelist: []
};
// 상태 변수
let crawlInProgress = false;
let currentPage = 1;
let totalPages = 1;
let visitedUrls = new Set();
let collectedData = [];
let logs = [];
// ============================
// UI 생성
// ============================
const uiContainer = document.createElement('div');
uiContainer.id = 'crawler-ui';
uiContainer.style.position = 'fixed';
uiContainer.style.top = '10px';
uiContainer.style.right = '10px';
uiContainer.style.width = '400px';
uiContainer.style.height = '600px';
uiContainer.style.backgroundColor = '#f9f9f9';
uiContainer.style.border = '1px solid #ccc';
uiContainer.style.borderRadius = '8px';
uiContainer.style.boxShadow = '0 0 10px rgba(0,0,0,0.1)';
uiContainer.style.zIndex = '10000';
uiContainer.style.fontFamily = 'Arial, sans-serif';
uiContainer.style.display = 'flex';
uiContainer.style.flexDirection = 'column';
// 탭 메뉴
const tabMenu = document.createElement('div');
tabMenu.style.display = 'flex';
tabMenu.style.borderBottom = '1px solid #ccc';
const tabs = ['📜 로그', '📊 데이터', '⚙️ 설정'];
tabs.forEach((tabName, index) => {
const tab = document.createElement('div');
tab.innerText = tabName;
tab.style.flex = '1';
tab.style.padding = '10px';
tab.style.cursor = 'pointer';
tab.style.textAlign = 'center';
tab.style.userSelect = 'none';
tab.style.backgroundColor = index === 0 ? '#e0e0e0' : '#f9f9f9';
tab.style.transition = 'background-color 0.3s';
tab.addEventListener('click', () => switchTab(index));
tab.addEventListener('mouseover', () => {
if (activeTab !== index) tab.style.backgroundColor = '#d0d0d0';
});
tab.addEventListener('mouseout', () => {
if (activeTab !== index) tab.style.backgroundColor = '#f9f9f9';
});
tabMenu.appendChild(tab);
});
uiContainer.appendChild(tabMenu);
// 탭 콘텐츠
const tabContents = [];
// 로그 탭
const logTab = document.createElement('div');
logTab.style.flex = '1';
logTab.style.padding = '10px';
logTab.style.overflowY = 'auto';
logTab.style.display = 'block';
tabContents.push(logTab);
uiContainer.appendChild(logTab);
// 데이터 탭
const dataTab = document.createElement('div');
dataTab.style.flex = '1';
dataTab.style.padding = '10px';
dataTab.style.overflowY = 'auto';
dataTab.style.display = 'none';
tabContents.push(dataTab);
uiContainer.appendChild(dataTab);
// 설정 탭
const settingsTab = document.createElement('div');
settingsTab.style.flex = '1';
settingsTab.style.padding = '10px';
settingsTab.style.overflowY = 'auto';
settingsTab.style.display = 'none';
tabContents.push(settingsTab);
uiContainer.appendChild(settingsTab);
document.body.appendChild(uiContainer);
let activeTab = 0;
function switchTab(index) {
tabContents[activeTab].style.display = 'none';
tabMenu.children[activeTab].style.backgroundColor = '#f9f9f9';
activeTab = index;
tabContents[activeTab].style.display = 'block';
tabMenu.children[activeTab].style.backgroundColor = '#e0e0e0';
}
// ============================
// 로그 기능
// ============================
function log(message, type='info') {
const logEntry = document.createElement('div');
logEntry.innerText = `[${new Date().toLocaleTimeString()}] ${message}`;
if (type === 'error') {
logEntry.style.color = 'red';
} else if (type === 'success') {
logEntry.style.color = 'green';
}
logTab.appendChild(logEntry);
logTab.scrollTop = logTab.scrollHeight;
logs.push({ timestamp: new Date(), message, type });
GM_setValue('logs', JSON.stringify(logs));
}
// ============================
// 데이터 테이블
// ============================
const table = document.createElement('table');
table.style.width = '100%';
table.style.borderCollapse = 'collapse';
table.style.marginBottom = '10px';
const headerRow = document.createElement('tr');
const headers = ['사이트 이름', '주소', '설명', 'HTML 내용', '텍스트 내용', '분류'];
headers.forEach(headerText => {
const th = document.createElement('th');
th.innerText = headerText;
th.style.border = '1px solid #ccc';
th.style.padding = '8px';
th.style.backgroundColor = '#f0f0f0';
th.style.textAlign = 'left';
headerRow.appendChild(th);
});
table.appendChild(headerRow);
dataTab.appendChild(table);
// 검색 입력 필드
const searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.placeholder = '검색...';
searchInput.style.width = '100%';
searchInput.style.padding = '8px';
searchInput.style.marginBottom = '10px';
searchInput.title = '키워드 입력 시 실시간 필터링';
searchInput.addEventListener('input', filterTable);
dataTab.insertBefore(searchInput, table);
function filterTable() {
const query = searchInput.value.toLowerCase();
const rows = table.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
const cells = rows[i].getElementsByTagName('td');
let match = false;
for (let j = 0; j < cells.length; j++) {
if (cells[j].innerText.toLowerCase().includes(query)) {
match = true;
break;
}
}
rows[i].style.display = match ? '' : 'none';
}
}
function addDataRow(data) {
const row = document.createElement('tr');
const siteNameCell = document.createElement('td');
siteNameCell.innerText = data.name;
siteNameCell.style.border = '1px solid #ccc';
siteNameCell.style.padding = '8px';
row.appendChild(siteNameCell);
const urlCell = document.createElement('td');
urlCell.innerText = data.url;
urlCell.style.border = '1px solid #ccc';
urlCell.style.padding = '8px';
row.appendChild(urlCell);
const descriptionCell = document.createElement('td');
descriptionCell.innerText = data.description;
descriptionCell.style.border = '1px solid #ccc';
descriptionCell.style.padding = '8px';
row.appendChild(descriptionCell);
const htmlCell = document.createElement('td');
htmlCell.innerText = '보기';
htmlCell.style.border = '1px solid #ccc';
htmlCell.style.padding = '8px';
htmlCell.style.cursor = 'pointer';
htmlCell.title = 'HTML 내용 보기';
htmlCell.addEventListener('click', () => showModal(data.html));
row.appendChild(htmlCell);
const textCell = document.createElement('td');
textCell.innerText = data.text;
textCell.style.border = '1px solid #ccc';
textCell.style.padding = '8px';
row.appendChild(textCell);
const categoryCell = document.createElement('td');
categoryCell.innerText = data.category;
categoryCell.style.border = '1px solid #ccc';
categoryCell.style.padding = '8px';
row.appendChild(categoryCell);
table.appendChild(row);
}
// ============================
// 모달 창 (HTML 내용 보기)
// ============================
const modal = document.createElement('div');
modal.id = 'crawler-modal';
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
modal.style.display = 'none';
modal.style.justifyContent = 'center';
modal.style.alignItems = 'center';
modal.style.zIndex = '10001';
const modalContent = document.createElement('div');
modalContent.style.width = '80%';
modalContent.style.height = '80%';
modalContent.style.backgroundColor = '#fff';
modalContent.style.borderRadius = '8px';
modalContent.style.padding = '20px';
modalContent.style.overflowY = 'auto';
modalContent.style.position = 'relative';
const closeModal = document.createElement('span');
closeModal.innerHTML = '×';
closeModal.style.position = 'absolute';
closeModal.style.top = '10px';
closeModal.style.right = '20px';
closeModal.style.fontSize = '30px';
closeModal.style.cursor = 'pointer';
closeModal.addEventListener('click', () => {
modal.style.display = 'none';
});
const modalBody = document.createElement('pre');
modalBody.style.whiteSpace = 'pre-wrap';
modalBody.style.wordWrap = 'break-word';
modalContent.appendChild(closeModal);
modalContent.appendChild(modalBody);
modal.appendChild(modalContent);
document.body.appendChild(modal);
function showModal(content) {
modalBody.innerText = content;
modal.style.display = 'flex';
}
// ============================
// 설정 탭
// ============================
const settingsForm = document.createElement('form');
// 크롤링 딜레이 설정
const delayLabel = document.createElement('label');
delayLabel.innerText = '크롤링 딜레이 (ms): ';
const delayInput = document.createElement('input');
delayInput.type = 'number';
delayInput.value = settings.crawlDelay;
delayInput.min = '1000';
delayInput.style.width = '100%';
delayInput.style.marginBottom = '10px';
delayInput.title = '크롤링 딜레이를 밀리초 단위로 설정';
delayLabel.appendChild(document.createElement('br'));
delayLabel.appendChild(delayInput);
settingsForm.appendChild(delayLabel);
// 블랙리스트 설정
const blacklistLabel = document.createElement('label');
blacklistLabel.innerText = '블랙리스트 도메인 (콤마로 구분): ';
const blacklistInput = document.createElement('input');
blacklistInput.type = 'text';
blacklistInput.value = settings.blacklist.join(',');
blacklistInput.style.width = '100%';
blacklistInput.style.marginBottom = '10px';
blacklistInput.title = '크롤링 제외 도메인';
blacklistLabel.appendChild(document.createElement('br'));
blacklistLabel.appendChild(blacklistInput);
settingsForm.appendChild(blacklistLabel);
// 화이트리스트 설정
const whitelistLabel = document.createElement('label');
whitelistLabel.innerText = '화이트리스트 도메인 (콤마로 구분): ';
const whitelistInput = document.createElement('input');
whitelistInput.type = 'text';
whitelistInput.value = settings.whitelist.join(',');
whitelistInput.style.width = '100%';
whitelistInput.style.marginBottom = '10px';
whitelistInput.title = '크롤링 허용 도메인';
whitelistLabel.appendChild(document.createElement('br'));
whitelistLabel.appendChild(whitelistInput);
settingsForm.appendChild(whitelistLabel);
// 저장 버튼
const saveButton = document.createElement('button');
saveButton.type = 'button';
saveButton.innerText = '저장';
saveButton.style.padding = '10px 20px';
saveButton.style.cursor = 'pointer';
saveButton.addEventListener('click', () => {
settings.crawlDelay = parseInt(delayInput.value) || 3000;
settings.blacklist = blacklistInput.value.split(',').map(s => s.trim()).filter(s => s);
settings.whitelist = whitelistInput.value.split(',').map(s => s.trim()).filter(s => s);
log('설정을 저장했습니다.', 'success');
});
settingsForm.appendChild(saveButton);
settingsTab.appendChild(settingsForm);
// ============================
// 진행률 바
// ============================
const progressContainer = document.createElement('div');
progressContainer.style.position = 'fixed';
progressContainer.style.left = '10px';
progressContainer.style.top = '10px';
progressContainer.style.width = '200px';
progressContainer.style.height = '20px';
progressContainer.style.backgroundColor = '#e0e0e0';
progressContainer.style.borderRadius = '10px';
progressContainer.style.overflow = 'hidden';
progressContainer.style.zIndex = '10002';
const progressBar = document.createElement('div');
progressBar.style.width = '0%';
progressBar.style.height = '100%';
progressBar.style.backgroundColor = '#76c7c0';
progressBar.style.transition = 'width 0.3s';
progressContainer.appendChild(progressBar);
const progressText = document.createElement('span');
progressText.style.position = 'absolute';
progressText.style.left = '50%';
progressText.style.top = '0';
progressText.style.transform = 'translateX(-50%)';
progressText.style.fontSize = '12px';
progressText.style.lineHeight = '20px';
progressText.innerText = '0%';
progressContainer.appendChild(progressText);
document.body.appendChild(progressContainer);
function updateProgress(percent) {
progressBar.style.width = `${percent}%`;
progressText.innerText = `${percent}%`;
}
// ============================
// 키보드 단축키
// ============================
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
// 설정 저장
saveButton.click();
}
if (e.ctrlKey && e.key === 'p') {
e.preventDefault();
// 크롤링 시작
startCrawling();
}
if (e.ctrlKey && e.key === 'q') {
e.preventDefault();
// 크롤링 중지
stopCrawling();
}
if (e.ctrlKey && e.key === 'd') {
e.preventDefault();
// CSV 다운로드
downloadCSV();
}
if (e.ctrlKey && e.key === 'j') {
e.preventDefault();
// JSON 다운로드
downloadJSON();
}
if (e.ctrlKey && e.key === '1') {
e.preventDefault();
switchTab(0);
}
if (e.ctrlKey && e.key === '2') {
e.preventDefault();
switchTab(1);
}
if (e.ctrlKey && e.key === '3') {
e.preventDefault();
switchTab(2);
}
});
// ============================
// 크롤링 기능
// ============================
async function startCrawling() {
if (crawlInProgress) {
log('크롤링이 이미 진행 중입니다.', 'error');
return;
}
crawlInProgress = true;
log('크롤링을 시작합니다...', 'info');
currentPage = 1;
totalPages = settings.maxPages;
collectedData = [];
visitedUrls = new Set();
updateProgress(0);
await crawlPage(currentPage);
}
function stopCrawling() {
if (!crawlInProgress) {
log('크롤링이 진행 중이지 않습니다.', 'error');
return;
}
crawlInProgress = false;
log('크롤링을 중지했습니다.', 'info');
}
async function crawlPage(pageNumber) {
if (!crawlInProgress || pageNumber > totalPages) {
crawlInProgress = false;
log('크롤링이 완료되었습니다.', 'success');
return;
}
const searchQuery = prompt('검색어를 입력하세요:', 'example');
if (searchQuery === null) {
stopCrawling();
return;
}
const searchUrl = `https://www.example.com/search?q=${encodeURIComponent(searchQuery)}&page=${pageNumber}`;
if (isBlacklisted(searchUrl) || !isWhitelisted(searchUrl)) {
log(`페이지 ${pageNumber}은(는) 블랙리스트에 포함되어 있거나 화이트리스트에 포함되지 않았습니다.`, 'error');
crawlInProgress = false;
return;
}
try {
const response = await fetch(searchUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 예시: 검색 결과에서 링크 추출
const links = Array.from(doc.querySelectorAll('a'));
for (let link of links) {
const url = link.href;
if (visitedUrls.has(url) || isBlacklisted(url) || !isWhitelisted(url)) continue;
visitedUrls.add(url);
try {
const pageResponse = await fetch(url);
const pageHtml = await pageResponse.text();
const pageDoc = parser.parseFromString(pageHtml, 'text/html');
const textContent = pageDoc.body.innerText;
const description = pageDoc.querySelector('meta[name="description"]')?.content || '설명 없음';
const name = pageDoc.title || '제목 없음';
const category = classifyKeywords(description);
const dataEntry = {
name,
url,
description,
html: pageHtml,
text: textContent,
category
};
collectedData.push(dataEntry);
addDataRow(dataEntry);
log(`데이터 수집 완료: ${url}`, 'success');
} catch (err) {
log(`페이지 수집 오류 (${url}): ${err.message}`, 'error');
}
// 진행률 업데이트
const percent = Math.min(100, Math.floor((collectedData.length / settings.maxPages) * 100));
updateProgress(percent);
}
// 다음 페이지로 이동
currentPage++;
await delay(settings.crawlDelay);
crawlPage(currentPage);
} catch (err) {
log(`크롤링 오류: ${err.message}`, 'error');
crawlInProgress = false;
}
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function isBlacklisted(url) {
return settings.blacklist.some(domain => url.includes(domain));
}
function isWhitelisted(url) {
if (settings.whitelist.length === 0) return true;
return settings.whitelist.some(domain => url.includes(domain));
}
// ============================
// 데이터 다운로드
// ============================
function downloadCSV() {
const headers = ['사이트 이름', '주소', '설명', 'HTML 내용', '텍스트 내용', '분류'];
const rows = collectedData.map(d => [
`"${d.name.replace(/"/g, '""')}"`,
`"${d.url.replace(/"/g, '""')}"`,
`"${d.description.replace(/"/g, '""')}"`,
`"${d.html.replace(/"/g, '""')}"`,
`"${d.text.replace(/"/g, '""')}"`,
`"${d.category.replace(/"/g, '""')}"`,
].join(','));
const csvContent = [headers.join(','), ...rows].join('\n');
GM_download({
url: 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvContent),
name: 'data.csv',
saveAs: true
});
log('CSV 파일을 다운로드했습니다.', 'success');
}
function downloadJSON() {
const jsonContent = JSON.stringify(collectedData, null, 2);
GM_download({
url: 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonContent),
name: 'data.json',
saveAs: true
});
log('JSON 파일을 다운로드했습니다.', 'success');
}
// ============================
// 콘텐츠 품질 평가 및 자동 분류
// ============================
function evaluateContentQuality(text) {
const wordCount = text.split(/\s+/).length;
return wordCount > 500 ? 'High' : 'Low';
}
function classifyKeywords(description) {
const keywords = ['교육', '게임', '뉴스', '블로그', '쇼핑'];
for (let keyword of keywords) {
if (description.includes(keyword)) return keyword;
}
return '기타';
}
// ============================
// 중복 검사
// ============================
// 이미 visitedUrls를 사용하여 중복 검사
// ============================
// 초기화 함수
// ============================
function initialize() {
// 불러온 로그
const savedLogs = JSON.parse(GM_getValue('logs', '[]'));
savedLogs.forEach(logEntry => {
log(logEntry.message, logEntry.type);
});
// 사용자 인터페이스 최적화
makeUIImprovements();
}
function makeUIImprovements() {
// 데이터 테이블 스타일 개선
table.style.width = '100%';
table.style.borderCollapse = 'collapse';
table.querySelectorAll('th, td').forEach(cell => {
cell.style.border = '1px solid #ccc';
cell.style.padding = '8px';
cell.style.textAlign = 'left';
});
// 스크롤바 추가
dataTab.style.overflowY = 'auto';
logTab.style.overflowY = 'auto';
settingsTab.style.overflowY = 'auto';
}
// ============================
// 에러 핸들링 강화
// ============================
window.addEventListener('error', function(e) {
log(`전역 에러 발생: ${e.message}`, 'error');
});
// ============================
// 실행
// ============================
initialize();
})();