// ==UserScript== // @name Comprehensive Web Crawler //… · The Chat Archive// ==UserScript== // @name Comprehensive Web Crawler // @namespace…
Download ▾
Assistant
// 설정
const SETTINGS = {
crawlDelay: 3000, // 3초 대기
maxPages: 100, // 최대 페이지 수
blacklist: [], // 블랙리스트 도메인
whitelist: [] // 화이트리스트 도메인
};
// 상태 변수
let isCrawling = false;
let currentPage = 1;
let totalPages = 1;
let progress = 0;
let collectedData = [];
let visitedURLs = new Set();
let logs = [];
// UI 생성
const createUI = () => {
// 스타일 추가
const style = `
#crawlerUI {
position: fixed;
top: 10px;
right: 10px;
width: 400px;
height: 600px;
background: white;
border: 1px solid #ccc;
z-index: 9999;
font-family: Arial, sans-serif;
}
#crawlerTabs {
display: flex;
background: #f1f1f1;
cursor: pointer;
}
.crawlerTab {
flex: 1;
padding: 10px;
text-align: center;
border-right: 1px solid #ccc;
}
.crawlerTab:last-child {
border-right: none;
}
.crawlerTab.active {
background: #fff;
font-weight: bold;
}
#crawlerContent > div {
display: none;
padding: 10px;
height: 540px;
overflow-y: auto;
}
#crawlerContent > div.active {
display: block;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ccc;
}
th, td {
padding: 8px;
text-align: left;
}
#progressBarContainer {
width: 100%;
background-color: #f3f3f3;
border: 1px solid #ccc;
margin-top: 10px;
}
#progressBar {
width: 0%;
height: 20px;
background-color: #4caf50;
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
`;
const styleElem = document.createElement('style');
styleElem.innerHTML = style;
document.head.appendChild(styleElem);
// UI 구조
const ui = `
<div id="crawlerUI">
<div id="crawlerTabs">
<div class="crawlerTab active" data-tab="logs">📜 로그</div>
<div class="crawlerTab" data-tab="data">📊 데이터</div>
<div class="crawlerTab" data-tab="settings">⚙️ 설정</div>
</div>
<div id="crawlerContent">
<div id="logs" class="active">
<ul id="logList"></ul>
</div>
<div id="data">
<input type="text" id="searchInput" placeholder="검색..." style="width: 100%; padding: 5px; margin-bottom: 10px;">
<table id="dataTable">
<thead>
<tr>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>분류</th>
<th>품질 점수</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="settings">
<label>크롤링 속도 (ms): <input type="number" id="crawlDelayInput" value="${SETTINGS.crawlDelay}" min="1000"></label><br><br>
<label>블랙리스트 도메인 (쉼표로 구분): <input type="text" id="blacklistInput" value="${SETTINGS.blacklist.join(', ')}" style="width: 100%;"></label><br><br>
<label>화이트리스트 도메인 (쉼표로 구분): <input type="text" id="whitelistInput" value="${SETTINGS.whitelist.join(', ')}" style="width: 100%;"></label><br><br>
<button id="saveSettings">설정 저장 (Ctrl+S)</button>
</div>
</div>
<div id="progressBarContainer">
<div id="progressBar"></div>
</div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', ui);
// 탭 전환 이벤트
document.querySelectorAll('.crawlerTab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.crawlerTab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const tabName = tab.getAttribute('data-tab');
document.querySelectorAll('#crawlerContent > div').forEach(content => {
if(content.id === tabName){
content.classList.add('active');
} else {
content.classList.remove('active');
}
});
});
});
// 설정 저장 버튼
document.getElementById('saveSettings').addEventListener('click', saveSettings);
// 검색 필터
document.getElementById('searchInput').addEventListener('input', filterTable);
};
// 설정 저장 함수
const saveSettings = () => {
SETTINGS.crawlDelay = parseInt(document.getElementById('crawlDelayInput').value) || 3000;
SETTINGS.blacklist = document.getElementById('blacklistInput').value.split(',').map(s => s.trim()).filter(s => s);
SETTINGS.whitelist = document.getElementById('whitelistInput').value.split(',').map(s => s.trim()).filter(s => s);
log(`설정이 저장되었습니다.`);
};
// 로그 추가 함수
const log = (message, type = 'info') => {
logs.push({message, type});
const logList = document.getElementById('logList');
const li = document.createElement('li');
li.textContent = message;
if(type === 'error') li.style.color = 'red';
logList.appendChild(li);
};
// 데이터 추가 함수
const addData = (data) => {
collectedData.push(data);
updateDataTable();
};
// 데이터 테이블 업데이트
const updateDataTable = () => {
const tbody = document.querySelector('#dataTable tbody');
tbody.innerHTML = '';
collectedData.forEach((data, index) => {
const tr = document.createElement('tr');
const nameTd = document.createElement('td');
nameTd.textContent = data.name;
tr.appendChild(nameTd);
const urlTd = document.createElement('td');
const link = document.createElement('a');
link.href = data.url;
link.textContent = data.url;
link.target = '_blank';
urlTd.appendChild(link);
tr.appendChild(urlTd);
const descTd = document.createElement('td');
descTd.textContent = data.description;
tr.appendChild(descTd);
const categoryTd = document.createElement('td');
categoryTd.textContent = data.category;
tr.appendChild(categoryTd);
const qualityTd = document.createElement('td');
qualityTd.textContent = data.qualityScore;
tr.appendChild(qualityTd);
tbody.appendChild(tr);
});
};
// 테이블 필터링 함수
const filterTable = () => {
const keyword = document.getElementById('searchInput').value.toLowerCase();
const rows = document.querySelectorAll('#dataTable tbody tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
const match = Array.from(cells).some(td => td.textContent.toLowerCase().includes(keyword));
row.style.display = match ? '' : 'none';
});
};
// 진행률 업데이트
const updateProgress = () => {
progress = (currentPage / totalPages) * 100;
document.getElementById('progressBar').style.width = `${progress}%`;
};
// 크롤링 시작 함수
const startCrawling = async (searchKeyword) => {
if(isCrawling) {
log('이미 크롤링이 진행 중입니다.', 'error');
return;
}
isCrawling = true;
currentPage = 1;
progress = 0;
collectedData = [];
visitedURLs.clear();
log(`크롤링 시작: "${searchKeyword}"`);
while(currentPage <= totalPages && isCrawling) {
log(`페이지 ${currentPage} 수집 중...`);
try {
// 검색 페이지 로드
const searchUrl = `https://www.example.com/search?q=${encodeURIComponent(searchKeyword)}&page=${currentPage}`;
await loadPage(searchUrl);
// 데이터 수집
const results = collectDataFromPage();
totalPages = getTotalPages(); // 페이지 수 업데이트
for(const result of results) {
if(visitedURLs.has(result.url)) {
log(`중복된 URL 발견: ${result.url}`, 'error');
continue;
}
if(SETTINGS.whitelist.length > 0 && !SETTINGS.whitelist.some(domain => result.url.includes(domain))) {
log(`화이트리스트에 없는 도메인: ${result.url}`, 'error');
continue;
}
if(SETTINGS.blacklist.some(domain => result.url.includes(domain))) {
log(`블랙리스트 도메인: ${result.url}`, 'error');
continue;
}
visitedURLs.add(result.url);
const pageContent = await fetchPageContent(result.url);
const description = extractDescription(pageContent);
const qualityScore = evaluateContentQuality(description);
const category = classifyKeywords(description);
addData({
name: result.name,
url: result.url,
description: description,
category: category,
qualityScore: qualityScore
});
await delay(SETTINGS.crawlDelay);
}
updateProgress();
currentPage++;
} catch(error) {
log(`에러 발생: ${error.message}`, 'error');
}
}
isCrawling = false;
log('크롤링이 완료되었습니다.');
};
// 크롤링 중지 함수
const stopCrawling = () => {
if(isCrawling) {
isCrawling = false;
log('크롤링이 중지되었습니다.');
}
};
// 초기화 함수
const initialize = () => {
createUI();
addKeyboardShortcuts();
log('크롤러 초기화 완료.');
};
// 키보드 단축키 설정
const addKeyboardShortcuts = () => {
document.addEventListener('keydown', (e) => {
if(e.ctrlKey) {
switch(e.key.toLowerCase()) {
case 's':
e.preventDefault();
saveSettings();
break;
case 'p':
e.preventDefault();
const keyword = prompt('검색어를 입력하세요:');
if(keyword) startCrawling(keyword);
break;
case 'q':
e.preventDefault();
stopCrawling();
break;
case 'd':
e.preventDefault();
downloadCSV();
break;
case 'j':
e.preventDefault();
downloadJSON();
break;
case '1':
e.preventDefault();
activateTab('logs');
break;
case '2':
e.preventDefault();
activateTab('data');
break;
case '3':
e.preventDefault();
activateTab('settings');
break;
}
}
});
};
// 탭 활성화 함수
const activateTab = (tabName) => {
document.querySelectorAll('.crawlerTab').forEach(tab => {
if(tab.getAttribute('data-tab') === tabName){
tab.click();
}
});
};
// CSV 다운로드
const downloadCSV = () => {
const csv = Papa.unparse(collectedData);
GM_download({
url: 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv),
name: 'data.csv',
saveAs: true
});
log('CSV 파일이 다운로드되었습니다.');
};
// JSON 다운로드
const downloadJSON = () => {
const json = JSON.stringify(collectedData, null, 2);
GM_download({
url: 'data:application/json;charset=utf-8,' + encodeURIComponent(json),
name: 'data.json',
saveAs: true
});
log('JSON 파일이 다운로드되었습니다.');
};
// 페이지 로드 함수
const loadPage = (url) => {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.text())
.then(html => {
// DOM 파싱
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
document.documentElement.innerHTML = doc.documentElement.innerHTML;
resolve();
})
.catch(err => reject(err));
});
};
// 데이터 수집 함수 (사이트 이름과 URL)
const collectDataFromPage = () => {
// 여기서는 예시로 검색 결과의 링크를 수집합니다.
// 실제 사이트 구조에 맞게 수정해야 합니다.
const results = [];
document.querySelectorAll('a.result-link').forEach(link => {
results.push({
name: link.textContent.trim(),
url: link.href
});
});
return results;
};
// 전체 페이지 수 가져오기
const getTotalPages = () => {
// 여기서는 예시로 총 페이지 수를 가져옵니다.
// 실제 사이트 구조에 맞게 수정해야 합니다.
const total = parseInt(document.querySelector('.total-pages').textContent.trim()) || 1;
return Math.min(total, SETTINGS.maxPages);
};
// 페이지 내용 가져오기
const fetchPageContent = async (url) => {
const response = await fetch(url);
return await response.text();
};
// 설명 추출 함수
const extractDescription = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 실제 사이트 구조에 맞게 수정
const desc = doc.querySelector('meta[name="description"]')?.getAttribute('content') || '설명 없음';
return desc;
};
// 콘텐츠 품질 평가 함수
const evaluateContentQuality = (text) => {
const wordCount = text.split(/\s+/).length;
return wordCount >= 100 ? '높음' : '낮음';
};
// 키워드 분류 함수
const classifyKeywords = (text) => {
const keywords = ['교육', '테크', '게임', '뉴스']; // 예시 키워드
for(const keyword of keywords) {
if(text.includes(keyword)) {
return keyword;
}
}
return '기타';
};
// 지연 함수
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 에러 핸들링 강화 (자동 재시도 등)
window.addEventListener('error', (e) => {
log(`전역 에러: ${e.message}`, 'error');
});
// 초기화 호출
initialize();
})(); 창 조절 기능 추가. 내가 크롤링 하고 있는 사이트들의 UI를 한 눈에 알아볼 수 있는 기능 추가
크롤러 스크립트에 창 조절 기능과 크롤링 중인 사이트들의 UI를 한 눈에 알아볼 수 있는 기능을 추가하려면 몇 가지 수정이 필요합니다. 아래에 단계별로 설명과 함께 필요한 코드를 제공하겠습니다.
1. 창 조절(Resizable) 기능 추가
UI 창을 사용자가 자유롭게 크기 조절할 수 있도록 하기 위해, CSS와 JavaScript를 활용하여 드래그 가능한 핸들을 추가할 수 있습니다.
수정 사항:
-
CSS 스타일 추가:
- 창의 오른쪽 하단에 드래그 핸들을 추가합니다.
cursor: se-resize 스타일을 적용하여 크기 조절 가능임을 표시합니다.
-
JavaScript 이벤트 핸들러 추가:
- 마우스 이벤트를 통해 창의 크기를 동적으로 조절합니다.
코드 예시:
javascript
// CSS 스타일에 드래그 핸들 추가
const style = `
/* 기존 스타일 ... */
/* Resizable 핸들 스타일 */
#resizeHandle {
position: absolute;
width: 20px;
height: 20px;
right: 0;
bottom: 0;
cursor: se-resize;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><line x1="0" y1="20" x2="20" y2="0" stroke="%23ccc" stroke-width="2"/></svg>') no-repeat center center;
}
`;
// UI 구조에 드래그 핸들 추가
const ui = `
<div id="crawlerUI">
<!-- 기존 UI 요소들 -->
<div id="resizeHandle"></div>
</div>
`;
// JavaScript로 창 크기 조절 로직 추가
const makeResizable = () => {
const resizer = document.getElementById('resizeHandle');
const ui = document.getElementById('crawlerUI');
let original_width = 0;
let original_height = 0;
let original_x = 0;
let original_y = 0;
let original_mouse_x = 0;
let original_mouse_y = 0;
resizer.addEventListener('mousedown', function(e) {
e.preventDefault();
original_width = parseFloat(getComputedStyle(ui, null).getPropertyValue('width').replace('px', ''));
original_height = parseFloat(getComputedStyle(ui, null).getPropertyValue('height').replace('px', ''));
original_mouse_x = e.pageX;
original_mouse_y = e.pageY;
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
});
function resize(e) {
ui.style.width = (original_width + e.pageX - original_mouse_x) + 'px';
ui.style.height = (original_height + e.pageY - original_mouse_y) + 'px';
}
function stopResize() {
window.removeEventListener('mousemove', resize);
window.removeEventListener('mouseup', stopResize);
}
};
// 초기화 함수에서 makeResizable 호출
const initialize = () => {
createUI();
makeResizable(); // 창 조절 기능 활성화
addKeyboardShortcuts();
log('크롤러 초기화 완료.');
};
2. 크롤링 중인 사이트들의 UI를 한 눈에 알아볼 수 있는 기능 추가
크롤링한 사이트들의 UI를 시각적으로 확인하려면 다음과 같은 방법을 고려할 수 있습니다:
-
썸네일 표시:
- 각 크롤링된 사이트의 스크린샷을 캡처하여 UI 내에 썸네일로 표시합니다.
- 이를 위해 외부 API(예: Screenshot API)를 사용해야 합니다. 하지만 외부 API 사용은 비용이 발생할 수 있으며, 크로스 도메인 문제로 인해 직접 캡처는 어렵습니다.
-
Iframe 사용:
- 각 사이트를 iframe 내에 로드하여 UI에서 직접 표시합니다.
- 보안상의 이유로 많은 사이트가 iframe 내에서의 로드를 허용하지 않으므로, 제한된 사용 사례에만 적합합니다.
-
간략한 정보 표시:
- 사이트의 제목, 설명, 주요 이미지 등을 표시하여 시각적인 인사이트를 제공합니다.
이번에는 보안과 호환성을 고려하여, 각 크롤링된 사이트의 제목과 주요 이미지를 표시하는 간단한 기능을 추가해 보겠습니다.
수정 사항:
-
데이터 수집에 이미지 URL 추가:
-
UI 테이블에 이미지 컬럼 추가:
- 수집된 데이터에 이미지 URL을 포함시키고, 데이터 테이블에 표시합니다.
코드 예시:
설명:
-
Resizable 기능:
- 창의 오른쪽 하단에
#resizeHandle div를 추가하고, 이를 이용해 사용자가 창 크기를 조절할 수 있도록 합니다.
- 마우스 다운, 무브, 업 이벤트를 통해 창의 크기를 동적으로 변경합니다.
-
크롤링된 사이트의 UI 요약 정보:
- 각 크롤링된 사이트에서 주요 이미지(예:
og:image 메타 태그 또는 .main-image 클래스를 가진 이미지)를 추출합니다.
- 데이터 테이블에 이미지 컬럼을 추가하여 시각적인 정보를 제공합니다.
- 이미지가 없을 경우 기본 플레이스홀더 이미지를 표시합니다.
3. 전체 수정된 스크립트
위의 변경 사항을 반영한 전체 스크립트는 아래와 같습니다. 필요한 부분만 수정하였으며, 기존 기능은 그대로 유지됩니다.
4. 주의 사항 및 추가 고려 사항
-
보안 및 접근 권한:
- 크롤링하려는 사이트가
CORS 정책을 통해 외부 스크립트의 접근을 제한할 수 있습니다. 이 경우 Tampermonkey의 @connect 메타 태그를 활용하여 필요한 도메인을 명시적으로 허용해야 할 수 있습니다.
- 예시:
javascript
// @connect www.example.com
// @connect another-domain.com
-
크롤링 대상 사이트의 구조에 맞는 수정:
collectDataFromPage, getTotalPages, extractDescription, extractImage 등의 함수는 크롤링하려는 실제 사이트의 HTML 구조에 맞게 수정해야 합니다.
-
이미지 캡처 제한:
- 일부 사이트는 보안상 iframe 내에서의 로드를 금지하거나, 스크린샷 API 사용 시 비용이 발생할 수 있습니다. 따라서, 이미지 URL을 직접 추출하는 방식을 사용했습니다.
-
성능 최적화:
- 많은 데이터를 수집할 경우 UI 성능에 영향을 미칠 수 있으므로, 데이터 양에 따라 페이징이나 가상 스크롤링을 고려할 수 있습니다.
-
사용자 편의성:
- UI 크기가 너무 커지거나 작아지는 것을 방지하기 위해 최소 및 최대 크기 제한을 설정할 수 있습니다.
- 추가적인 기능(예: 데이터 정렬, 필터링 등)을 구현하여 사용성을 향상시킬 수 있습니다.
위의 수정 사항을 적용하면, 크롤러 UI를 사용자가 자유롭게 크기 조절할 수 있으며, 크롤링된 사이트들의 주요 이미지를 포함한 정보를 시각적으로 확인할 수 있습니다. 필요에 따라 추가적인 기능을 더 개발하여 크롤러의 유용성을 더욱 높일 수 있습니다.
Not yet included in a published release.
// 설정, 상태 변수, UI 생성 등 기존 코드 유지
// 데이터 추가 함수 수정 (이미지 URL 포함)
const addData = (data) => {
collectedData.push(data);
updateDataTable();
};
// 데이터 테이블 업데이트 함수 수정 (이미지 컬럼 추가)
const updateDataTable = () => {
const tbody = document.querySelector('#dataTable tbody');
tbody.innerHTML = '';
collectedData.forEach((data, index) => {
const tr = document.createElement('tr');
// 이미지 컬럼
const imgTd = document.createElement('td');
const img = document.createElement('img');
img.src = data.image || 'https://via.placeholder.com/50';
img.alt = '이미지 없음';
img.style.width = '50px';
img.style.height = '50px';
imgTd.appendChild(img);
tr.appendChild(imgTd);
// 기존 컬럼들 (사이트 이름, 주소 등)
const nameTd = document.createElement('td');
nameTd.textContent = data.name;
tr.appendChild(nameTd);
const urlTd = document.createElement('td');
const link = document.createElement('a');
link.href = data.url;
link.textContent = data.url;
link.target = '_blank';
urlTd.appendChild(link);
tr.appendChild(urlTd);
const descTd = document.createElement('td');
descTd.textContent = data.description;
tr.appendChild(descTd);
const categoryTd = document.createElement('td');
categoryTd.textContent = data.category;
tr.appendChild(categoryTd);
const qualityTd = document.createElement('td');
qualityTd.textContent = data.qualityScore;
tr.appendChild(qualityTd);
tbody.appendChild(tr);
});
};
// 데이터 수집 함수 수정 (이미지 URL 추출)
const collectDataFromPage = () => {
// 여기서는 예시로 검색 결과의 링크와 이미지를 수집합니다.
// 실제 사이트 구조에 맞게 수정해야 합니다.
const results = [];
document.querySelectorAll('a.result-link').forEach(link => {
const img = link.querySelector('img')?.src || '';
results.push({
name: link.textContent.trim(),
url: link.href,
image: img
});
});
return results;
};
// 크롤링 시작 함수 수정 (이미지 포함 데이터 수집)
const startCrawling = async (searchKeyword) => {
if(isCrawling) {
log('이미 크롤링이 진행 중입니다.', 'error');
return;
}
isCrawling = true;
currentPage = 1;
progress = 0;
collectedData = [];
visitedURLs.clear();
log(`크롤링 시작: "${searchKeyword}"`);
while(currentPage <= totalPages && isCrawling) {
log(`페이지 ${currentPage} 수집 중...`);
try {
// 검색 페이지 로드
const searchUrl = `https://www.example.com/search?q=${encodeURIComponent(searchKeyword)}&page=${currentPage}`;
await loadPage(searchUrl);
// 데이터 수집
const results = collectDataFromPage();
totalPages = getTotalPages(); // 페이지 수 업데이트
for(const result of results) {
if(visitedURLs.has(result.url)) {
log(`중복된 URL 발견: ${result.url}`, 'error');
continue;
}
if(SETTINGS.whitelist.length > 0 && !SETTINGS.whitelist.some(domain => result.url.includes(domain))) {
log(`화이트리스트에 없는 도메인: ${result.url}`, 'error');
continue;
}
if(SETTINGS.blacklist.some(domain => result.url.includes(domain))) {
log(`블랙리스트 도메인: ${result.url}`, 'error');
continue;
}
visitedURLs.add(result.url);
const pageContent = await fetchPageContent(result.url);
const description = extractDescription(pageContent);
const qualityScore = evaluateContentQuality(description);
const category = classifyKeywords(description);
const image = extractImage(pageContent); // 이미지 추출 함수
addData({
name: result.name,
url: result.url,
description: description,
category: category,
qualityScore: qualityScore,
image: image
});
await delay(SETTINGS.crawlDelay);
}
updateProgress();
currentPage++;
} catch(error) {
log(`에러 발생: ${error.message}`, 'error');
}
}
isCrawling = false;
log('크롤링이 완료되었습니다.');
};
// 이미지 추출 함수 추가
const extractImage = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 실제 사이트 구조에 맞게 추출 로직 수정
const imgSrc = doc.querySelector('meta[property="og:image"]')?.getAttribute('content') ||
doc.querySelector('img.main-image')?.src ||
'';
return imgSrc;
};
// 데이터 테이블 헤더 수정 (이미지 컬럼 추가)
const createUI = () => {
// 기존 스타일 유지 및 수정
const ui = `
<div id="crawlerUI">
<div id="crawlerTabs">
<div class="crawlerTab active" data-tab="logs">📜 로그</div>
<div class="crawlerTab" data-tab="data">📊 데이터</div>
<div class="crawlerTab" data-tab="settings">⚙️ 설정</div>
</div>
<div id="crawlerContent">
<div id="logs" class="active">
<ul id="logList"></ul>
</div>
<div id="data">
<input type="text" id="searchInput" placeholder="검색..." style="width: 100%; padding: 5px; margin-bottom: 10px;">
<table id="dataTable">
<thead>
<tr>
<th>이미지</th>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>분류</th>
<th>품질 점수</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="settings">
<label>크롤링 속도 (ms): <input type="number" id="crawlDelayInput" value="${SETTINGS.crawlDelay}" min="1000"></label><br><br>
<label>블랙리스트 도메인 (쉼표로 구분): <input type="text" id="blacklistInput" value="${SETTINGS.blacklist.join(', ')}" style="width: 100%;"></label><br><br>
<label>화이트리스트 도메인 (쉼표로 구분): <input type="text" id="whitelistInput" value="${SETTINGS.whitelist.join(', ')}" style="width: 100%;"></label><br><br>
<button id="saveSettings">설정 저장 (Ctrl+S)</button>
</div>
</div>
<div id="progressBarContainer">
<div id="progressBar"></div>
</div>
<div id="resizeHandle"></div> <!-- Resizable 핸들 -->
</div>
`;
document.body.insertAdjacentHTML('beforeend', ui);
// 기존 이벤트 리스너 등 유지
};
// ==UserScript==
// @name Comprehensive Web Crawler
// @namespace http://tampermonkey.net/
// @version 1.1
// @description 자동 웹 크롤링 및 데이터 수집 스크립트 with Resizable UI and Site Thumbnails
// @author Your Name
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_download
// @require https://cdnjs.cloudflare.com/ajax/libs/papaparse/5.3.2/papaparse.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==
(function() {
'use strict';
// 설정
const SETTINGS = {
crawlDelay: 3000, // 3초 대기
maxPages: 100, // 최대 페이지 수
blacklist: [], // 블랙리스트 도메인
whitelist: [] // 화이트리스트 도메인
};
// 상태 변수
let isCrawling = false;
let currentPage = 1;
let totalPages = 1;
let progress = 0;
let collectedData = [];
let visitedURLs = new Set();
let logs = [];
// UI 생성
const createUI = () => {
// 스타일 추가
const style = `
#crawlerUI {
position: fixed;
top: 10px;
right: 10px;
width: 600px;
height: 600px;
background: white;
border: 1px solid #ccc;
z-index: 9999;
font-family: Arial, sans-serif;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
#crawlerTabs {
display: flex;
background: #f1f1f1;
cursor: pointer;
}
.crawlerTab {
flex: 1;
padding: 10px;
text-align: center;
border-right: 1px solid #ccc;
}
.crawlerTab:last-child {
border-right: none;
}
.crawlerTab.active {
background: #fff;
font-weight: bold;
}
#crawlerContent > div {
display: none;
padding: 10px;
height: 510px;
overflow-y: auto;
}
#crawlerContent > div.active {
display: block;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ccc;
}
th, td {
padding: 8px;
text-align: left;
vertical-align: top;
}
#progressBarContainer {
width: 100%;
background-color: #f3f3f3;
border: 1px solid #ccc;
margin-top: 10px;
}
#progressBar {
width: 0%;
height: 20px;
background-color: #4caf50;
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
/* Resizable 핸들 스타일 */
#resizeHandle {
position: absolute;
width: 20px;
height: 20px;
right: 0;
bottom: 0;
cursor: se-resize;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><line x1="0" y1="20" x2="20" y2="0" stroke="%23ccc" stroke-width="2"/></svg>') no-repeat center center;
}
/* 데이터 테이블 이미지 컬럼 스타일 */
#dataTable img {
max-width: 50px;
max-height: 50px;
}
`;
const styleElem = document.createElement('style');
styleElem.innerHTML = style;
document.head.appendChild(styleElem);
// UI 구조
const ui = `
<div id="crawlerUI">
<div id="crawlerTabs">
<div class="crawlerTab active" data-tab="logs">📜 로그</div>
<div class="crawlerTab" data-tab="data">📊 데이터</div>
<div class="crawlerTab" data-tab="settings">⚙️ 설정</div>
</div>
<div id="crawlerContent">
<div id="logs" class="active">
<ul id="logList" style="list-style: none; padding: 0;"></ul>
</div>
<div id="data">
<input type="text" id="searchInput" placeholder="검색..." style="width: 100%; padding: 5px; margin-bottom: 10px;">
<table id="dataTable">
<thead>
<tr>
<th>이미지</th>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
<th>분류</th>
<th>품질 점수</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="settings">
<label>크롤링 속도 (ms): <input type="number" id="crawlDelayInput" value="${SETTINGS.crawlDelay}" min="1000"></label><br><br>
<label>블랙리스트 도메인 (쉼표로 구분): <input type="text" id="blacklistInput" value="${SETTINGS.blacklist.join(', ')}" style="width: 100%;"></label><br><br>
<label>화이트리스트 도메인 (쉼표로 구분): <input type="text" id="whitelistInput" value="${SETTINGS.whitelist.join(', ')}" style="width: 100%;"></label><br><br>
<button id="saveSettings">설정 저장 (Ctrl+S)</button>
</div>
</div>
<div id="progressBarContainer">
<div id="progressBar"></div>
</div>
<div id="resizeHandle"></div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', ui);
// 탭 전환 이벤트
document.querySelectorAll('.crawlerTab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.crawlerTab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const tabName = tab.getAttribute('data-tab');
document.querySelectorAll('#crawlerContent > div').forEach(content => {
if(content.id === tabName){
content.classList.add('active');
} else {
content.classList.remove('active');
}
});
});
});
// 설정 저장 버튼
document.getElementById('saveSettings').addEventListener('click', saveSettings);
// 검색 필터
document.getElementById('searchInput').addEventListener('input', filterTable);
};
// 설정 저장 함수
const saveSettings = () => {
SETTINGS.crawlDelay = parseInt(document.getElementById('crawlDelayInput').value) || 3000;
SETTINGS.blacklist = document.getElementById('blacklistInput').value.split(',').map(s => s.trim()).filter(s => s);
SETTINGS.whitelist = document.getElementById('whitelistInput').value.split(',').map(s => s.trim()).filter(s => s);
log(`설정이 저장되었습니다.`);
};
// 로그 추가 함수
const log = (message, type = 'info') => {
logs.push({message, type});
const logList = document.getElementById('logList');
const li = document.createElement('li');
li.textContent = message;
if(type === 'error') li.style.color = 'red';
logList.appendChild(li);
// 자동 스크롤
logList.scrollTop = logList.scrollHeight;
};
// 데이터 추가 함수
const addData = (data) => {
collectedData.push(data);
updateDataTable();
};
// 데이터 테이블 업데이트
const updateDataTable = () => {
const tbody = document.querySelector('#dataTable tbody');
tbody.innerHTML = '';
collectedData.forEach((data, index) => {
const tr = document.createElement('tr');
// 이미지 컬럼
const imgTd = document.createElement('td');
const img = document.createElement('img');
img.src = data.image || 'https://via.placeholder.com/50';
img.alt = '이미지 없음';
imgTd.appendChild(img);
tr.appendChild(imgTd);
// 사이트 이름
const nameTd = document.createElement('td');
nameTd.textContent = data.name;
tr.appendChild(nameTd);
// 주소
const urlTd = document.createElement('td');
const link = document.createElement('a');
link.href = data.url;
link.textContent = data.url;
link.target = '_blank';
urlTd.appendChild(link);
tr.appendChild(urlTd);
// 설명
const descTd = document.createElement('td');
descTd.textContent = data.description;
tr.appendChild(descTd);
// 분류
const categoryTd = document.createElement('td');
categoryTd.textContent = data.category;
tr.appendChild(categoryTd);
// 품질 점수
const qualityTd = document.createElement('td');
qualityTd.textContent = data.qualityScore;
tr.appendChild(qualityTd);
tbody.appendChild(tr);
});
};
// 테이블 필터링 함수
const filterTable = () => {
const keyword = document.getElementById('searchInput').value.toLowerCase();
const rows = document.querySelectorAll('#dataTable tbody tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
const match = Array.from(cells).some(td => td.textContent.toLowerCase().includes(keyword));
row.style.display = match ? '' : 'none';
});
};
// 진행률 업데이트
const updateProgress = () => {
progress = (currentPage / totalPages) * 100;
document.getElementById('progressBar').style.width = `${progress}%`;
};
// 크롤링 시작 함수
const startCrawling = async (searchKeyword) => {
if(isCrawling) {
log('이미 크롤링이 진행 중입니다.', 'error');
return;
}
isCrawling = true;
currentPage = 1;
progress = 0;
collectedData = [];
visitedURLs.clear();
log(`크롤링 시작: "${searchKeyword}"`);
while(currentPage <= totalPages && isCrawling) {
log(`페이지 ${currentPage} 수집 중...`);
try {
// 검색 페이지 로드
const searchUrl = `https://www.example.com/search?q=${encodeURIComponent(searchKeyword)}&page=${currentPage}`;
await loadPage(searchUrl);
// 데이터 수집
const results = collectDataFromPage();
totalPages = getTotalPages(); // 페이지 수 업데이트
for(const result of results) {
if(visitedURLs.has(result.url)) {
log(`중복된 URL 발견: ${result.url}`, 'error');
continue;
}
if(SETTINGS.whitelist.length > 0 && !SETTINGS.whitelist.some(domain => result.url.includes(domain))) {
log(`화이트리스트에 없는 도메인: ${result.url}`, 'error');
continue;
}
if(SETTINGS.blacklist.some(domain => result.url.includes(domain))) {
log(`블랙리스트 도메인: ${result.url}`, 'error');
continue;
}
visitedURLs.add(result.url);
const pageContent = await fetchPageContent(result.url);
const description = extractDescription(pageContent);
const qualityScore = evaluateContentQuality(description);
const category = classifyKeywords(description);
const image = extractImage(pageContent); // 이미지 추출 함수
addData({
name: result.name,
url: result.url,
description: description,
category: category,
qualityScore: qualityScore,
image: image
});
await delay(SETTINGS.crawlDelay);
}
updateProgress();
currentPage++;
} catch(error) {
log(`에러 발생: ${error.message}`, 'error');
}
}
isCrawling = false;
log('크롤링이 완료되었습니다.');
};
// 크롤링 중지 함수
const stopCrawling = () => {
if(isCrawling) {
isCrawling = false;
log('크롤링이 중지되었습니다.');
}
};
// 초기화 함수
const initialize = () => {
createUI();
makeResizable(); // 창 조절 기능 활성화
addKeyboardShortcuts();
log('크롤러 초기화 완료.');
};
// 키보드 단축키 설정
const addKeyboardShortcuts = () => {
document.addEventListener('keydown', (e) => {
if(e.ctrlKey) {
switch(e.key.toLowerCase()) {
case 's':
e.preventDefault();
saveSettings();
break;
case 'p':
e.preventDefault();
const keyword = prompt('검색어를 입력하세요:');
if(keyword) startCrawling(keyword);
break;
case 'q':
e.preventDefault();
stopCrawling();
break;
case 'd':
e.preventDefault();
downloadCSV();
break;
case 'j':
e.preventDefault();
downloadJSON();
break;
case '1':
e.preventDefault();
activateTab('logs');
break;
case '2':
e.preventDefault();
activateTab('data');
break;
case '3':
e.preventDefault();
activateTab('settings');
break;
}
}
});
};
// 탭 활성화 함수
const activateTab = (tabName) => {
document.querySelectorAll('.crawlerTab').forEach(tab => {
if(tab.getAttribute('data-tab') === tabName){
tab.click();
}
});
};
// CSV 다운로드
const downloadCSV = () => {
const csv = Papa.unparse(collectedData);
GM_download({
url: 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv),
name: 'data.csv',
saveAs: true
});
log('CSV 파일이 다운로드되었습니다.');
};
// JSON 다운로드
const downloadJSON = () => {
const json = JSON.stringify(collectedData, null, 2);
GM_download({
url: 'data:application/json;charset=utf-8,' + encodeURIComponent(json),
name: 'data.json',
saveAs: true
});
log('JSON 파일이 다운로드되었습니다.');
};
// 페이지 로드 함수
const loadPage = (url) => {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.text())
.then(html => {
// DOM 파싱
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 현재 문서의 body를 크롤링한 페이지의 body로 대체
document.body.innerHTML = doc.body.innerHTML;
resolve();
})
.catch(err => reject(err));
});
};
// 데이터 수집 함수 (사이트 이름, URL, 이미지)
const collectDataFromPage = () => {
// 여기서는 예시로 검색 결과의 링크와 이미지를 수집합니다.
// 실제 사이트 구조에 맞게 수정해야 합니다.
const results = [];
document.querySelectorAll('a.result-link').forEach(link => {
const img = link.querySelector('img')?.src || '';
results.push({
name: link.textContent.trim(),
url: link.href,
image: img
});
});
return results;
};
// 전체 페이지 수 가져오기
const getTotalPages = () => {
// 여기서는 예시로 총 페이지 수를 가져옵니다.
// 실제 사이트 구조에 맞게 수정해야 합니다.
const total = parseInt(document.querySelector('.total-pages')?.textContent.trim()) || 1;
return Math.min(total, SETTINGS.maxPages);
};
// 페이지 내용 가져오기
const fetchPageContent = async (url) => {
const response = await fetch(url);
return await response.text();
};
// 설명 추출 함수
const extractDescription = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 실제 사이트 구조에 맞게 수정
const desc = doc.querySelector('meta[name="description"]')?.getAttribute('content') || '설명 없음';
return desc;
};
// 콘텐츠 품질 평가 함수
const evaluateContentQuality = (text) => {
const wordCount = text.split(/\s+/).length;
return wordCount >= 100 ? '높음' : '낮음';
};
// 키워드 분류 함수
const classifyKeywords = (text) => {
const keywords = ['교육', '테크', '게임', '뉴스']; // 예시 키워드
for(const keyword of keywords) {
if(text.includes(keyword)) {
return keyword;
}
}
return '기타';
};
// 이미지 추출 함수
const extractImage = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// 실제 사이트 구조에 맞게 추출 로직 수정
const imgSrc = doc.querySelector('meta[property="og:image"]')?.getAttribute('content') ||
doc.querySelector('img.main-image')?.src ||
'';
return imgSrc;
};
// 지연 함수
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 창 조절 기능
const makeResizable = () => {
const resizer = document.getElementById('resizeHandle');
const ui = document.getElementById('crawlerUI');
let original_width = 0;
let original_height = 0;
let original_mouse_x = 0;
let original_mouse_y = 0;
resizer.addEventListener('mousedown', function(e) {
e.preventDefault();
original_width = parseFloat(getComputedStyle(ui, null).getPropertyValue('width').replace('px', ''));
original_height = parseFloat(getComputedStyle(ui, null).getPropertyValue('height').replace('px', ''));
original_mouse_x = e.pageX;
original_mouse_y = e.pageY;
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
});
function resize(e) {
const new_width = original_width + e.pageX - original_mouse_x;
const new_height = original_height + e.pageY - original_mouse_y;
ui.style.width = (new_width > 300 ? new_width : 300) + 'px'; // 최소 너비 300px
ui.style.height = (new_height > 300 ? new_height : 300) + 'px'; // 최소 높이 300px
}
function stopResize() {
window.removeEventListener('mousemove', resize);
window.removeEventListener('mouseup', stopResize);
}
};
// 에러 핸들링 강화 (자동 재시도 등)
window.addEventListener('error', (e) => {
log(`전역 에러: ${e.message}`, 'error');
});
// 초기화 호출
initialize();
})();