안녕하세요! 웹 크롤링을 통해 검색 결과를 자동으로 수집하고, 이를 엑셀과 유사한 UI로 표시하며 다양한 기능(진행률 표시, 로그 저장, 중복 검사, 속도 조절 등)을 구현하려는 시도는 교육적인 목적에 매우 유용할 수 있습니다. 아래에 Tampermonkey 스크립트를 작성하고, 추가 기능에 대한 아이디어와 구현 방법에 대해 설명드리겠습니다.
주의사항:
- 법적 이슈: 타인의 웹사이트를 크롤링할 때 해당 사이트의
robots.txt나 이용 약관을 준수해야 합니다. 무단 크롤링은 법적 문제가 될 수 있습니다.
- 기술적 제한: Tampermonkey는 브라우저 확장 프로그램으로, 크롤링의 완전한 자동화를 위해서는 한계가 있을 수 있습니다. 특히, 동적 페이지나 JavaScript로 로드되는 콘텐츠의 경우 추가적인 처리가 필요할 수 있습니다.
- 성능 고려: 많은 데이터를 크롤링할 경우 브라우저의 성능에 영향을 줄 수 있습니다. 속도 조절과 같은 기능 구현이 중요합니다.
이제 스크립트 예제와 추가 기능 구현 방법을 살펴보겠습니다.
Tampermonkey 스크립트 예제
아래는 기본적인 웹 크롤링 기능을 수행하는 Tampermonkey 스크립트 예제입니다. 이 스크립트는 특정 검색 페이지(예: Google 검색)에서 결과를 수집하고, 다음 페이지로 이동하여 모든 결과를 수집한 후 결과를 UI로 표시합니다.
// ==UserScript==
// @name 웹 크롤러 및 결과 표시기
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 검색 결과를 크롤링하고 엑셀 형태로 표시합니다.
// @author Your Name
// @match https://www.google.com/search*
// @grant GM_download
// @grant GM_xmlhttpRequest
// @connect *
// ==/UserScript==
(function() {
'use strict';
// 크롤링 상태 및 데이터 저장
let crawlData = [];
let crawledURLs = new Set();
let currentPage = 1;
let totalPages = 5; // 원하는 총 페이지 수
let isCrawling = false;
// UI 생성
function createUI() {
const container = document.createElement('div');
container.id = 'crawlerContainer';
container.style.position = 'fixed';
container.style.top = '10px';
container.style.right = '10px';
container.style.width = '300px';
container.style.height = '400px';
container.style.backgroundColor = 'white';
container.style.border = '1px solid #ccc';
container.style.zIndex = 10000;
container.style.padding = '10px';
container.style.overflowY = 'scroll';
container.style.boxShadow = '0 0 10px rgba(0,0,0,0.5)';
// 제목
const title = document.createElement('h3');
title.innerText = '크롤러 UI';
container.appendChild(title);
// 진행률 표시
const progress = document.createElement('div');
progress.id = 'crawlProgress';
progress.innerText = '진행률: 0%';
container.appendChild(progress);
// 데이터 표
const table = document.createElement('table');
table.id = 'crawlTable';
table.border = '1';
table.style.width = '100%';
table.style.borderCollapse = 'collapse';
const header = table.insertRow();
['사이트 이름', '주소', '설명'].forEach(text => {
const th = document.createElement('th');
th.innerText = text;
th.style.padding = '5px';
header.appendChild(th);
});
container.appendChild(table);
// 시작 버튼
const startButton = document.createElement('button');
startButton.innerText = '크롤링 시작';
startButton.onclick = startCrawling;
container.appendChild(startButton);
// 로그 영역
const log = document.createElement('div');
log.id = 'crawlLog';
log.style.marginTop = '10px';
log.style.height = '100px';
log.style.overflowY = 'scroll';
log.style.border = '1px solid #ccc';
log.style.padding = '5px';
container.appendChild(log);
document.body.appendChild(container);
}
// 로그 추가 함수
function addLog(message) {
const log = document.getElementById('crawlLog');
const p = document.createElement('p');
p.innerText = `[${new Date().toLocaleTimeString()}] ${message}`;
log.appendChild(p);
log.scrollTop = log.scrollHeight;
}
// 진행률 업데이트
function updateProgress() {
const progress = document.getElementById('crawlProgress');
const percent = Math.floor((currentPage / totalPages) * 100);
progress.innerText = `진행률: ${percent}%`;
}
// 데이터 추가 및 UI 갱신
function addData(name, url, description) {
if (crawledURLs.has(url)) {
addLog(`중복된 URL 발견: ${url}`);
return;
}
crawledURLs.add(url);
crawlData.push({ name, url, description });
const table = document.getElementById('crawlTable');
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
cell1.innerText = name;
cell2.innerHTML = `<a href="${url}" target="_blank">${url}</a>`;
cell3.innerText = description;
}
// 크롤링 시작 함수
async function startCrawling() {
if (isCrawling) return;
isCrawling = true;
addLog('크롤링 시작');
for (currentPage = 1; currentPage <= totalPages; currentPage++) {
addLog(`페이지 ${currentPage} 크롤링 중...`);
updateProgress();
await crawlCurrentPage();
await goToNextPage();
// 속도 조절을 위해 잠시 대기
await delay(2000);
}
addLog('크롤링 완료');
updateProgress();
isCrawling = false;
}
// 현재 페이지 크롤링 함수
function crawlCurrentPage() {
return new Promise((resolve) => {
// Google 검색 결과의 각 결과는 div.g 클래스를 가집니다.
const results = document.querySelectorAll('div.g');
results.forEach(result => {
const titleElement = result.querySelector('h3');
const linkElement = result.querySelector('a');
const descriptionElement = result.querySelector('.IsZvec');
if (titleElement && linkElement) {
const name = titleElement.innerText;
const url = linkElement.href;
const description = descriptionElement ? descriptionElement.innerText : '설명 없음';
addData(name, url, description);
}
});
resolve();
});
}
// 다음 페이지로 이동하는 함수
function goToNextPage() {
return new Promise((resolve) => {
const nextButton = document.querySelector('#pnnext');
if (nextButton) {
nextButton.click();
// 페이지 로드 대기
window.addEventListener('load', () => {
resolve();
}, { once: true });
} else {
addLog('다음 페이지 버튼을 찾을 수 없습니다.');
resolve();
}
});
}
// 딜레이 함수
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// UI 생성
createUI();
})();
스크립트 설명
-
메타 데이터:
@match: Google 검색 결과 페이지에 스크립트를 적용합니다. 필요에 따라 다른 검색 엔진으로 변경하세요.
-
크롤링 상태 변수:
crawlData: 수집된 데이터 저장.
crawledURLs: 중복 URL을 방지하기 위한 Set.
currentPage 및 totalPages: 현재 페이지와 총 크롤링할 페이지 수.
isCrawling: 크롤링 중 여부를 나타내는 플래그.
-
UI 생성:
- 고정된 위치에 크롤링 상태, 데이터 표, 시작 버튼, 로그 영역을 포함하는 컨테이너 생성.
- HTML 요소를 동적으로 생성하고 스타일을 적용하여 사용자 친화적인 인터페이스 제공.
-
로그 기능:
addLog 함수는 로그 메시지를 로그 영역에 추가하고, 최신 로그가 보이도록 스크롤을 조정합니다.
-
진행률 표시:
updateProgress 함수는 현재 페이지를 기준으로 진행률을 계산하고 표시합니다.
-
데이터 수집:
addData 함수는 사이트 이름, URL, 설명을 수집하여 테이블에 추가하고, 중복 URL을 방지합니다.
-
크롤링 로직:
startCrawling 함수는 총 페이지 수만큼 반복하여 현재 페이지를 크롤링하고 다음 페이지로 이동합니다.
crawlCurrentPage 함수는 현재 페이지의 검색 결과를 수집합니다.
goToNextPage 함수는 "다음" 버튼을 클릭하여 다음 페이지로 이동합니다.
-
속도 조절:
delay 함수는 페이지 전환 후 대기 시간을 설정하여 서버 과부화를 방지합니다.
사용자 인터페이스 개선
위 스크립트는 기본적인 기능을 제공합니다. 추가적인 사용자 경험 향상을 위해 다음과 같은 기능을 고려할 수 있습니다.
-
광고 사이트 걸러내기:
- 광고 사이트를 식별하는 로직을 추가하여 결과에서 제외할 수 있습니다. 예를 들어, 특정 키워드나 도메인을 필터링합니다.
-
남은 예상 시간 표시:
- 크롤링 속도와 남은 페이지 수를 기반으로 예상 시간을 계산하여 표시할 수 있습니다.
-
데이터 저장 및 내보내기:
- 수집된 데이터를 CSV 또는 엑셀 파일로 내보내는 기능을 추가할 수 있습니다. Tampermonkey의
GM_download 기능을 활용하면 가능합니다.
-
에러 처리 및 재시도 로직:
- 페이지 로드 실패 시 재시도하는 로직을 추가하여 안정성을 높일 수 있습니다.
추가 기능 구현 예제
아래는 수집된 데이터를 CSV 파일로 다운로드하는 기능을 추가한 예제입니다.
// CSV 다운로드 버튼 추가
const downloadButton = document.createElement('button');
downloadButton.innerText = 'CSV 다운로드';
downloadButton.onclick = downloadCSV;
container.appendChild(downloadButton);
// CSV 다운로드 함수
function downloadCSV() {
if (crawlData.length === 0) {
addLog('다운로드할 데이터가 없습니다.');
return;
}
const headers = ['사이트 이름', '주소', '설명'];
const rows = crawlData.map(item => [item.name, item.url, item.description]);
let csvContent = 'data:text/csv;charset=utf-8,';
csvContent += headers.join(',') + '\n';
rows.forEach(row => {
// CSV 형식에 맞게 각 항목을 따옴표로 감싸고 콤마로 구분
const formattedRow = row.map(field => `"${field.replace(/"/g, '""')}"`).join(',');
csvContent += formattedRow + '\n';
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement('a');
link.setAttribute('href', encodedUri);
link.setAttribute('download', 'crawl_data.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
이 코드를 기존 스크립트의 UI 생성 부분에 추가하면, 수집된 데이터를 CSV 파일로 다운로드할 수 있는 버튼이 추가됩니다.
추가적인 고려 사항
-
다양한 검색 엔진 지원:
- Google 외에도 다른 검색 엔진(예: Bing, Naver 등)에 대응하려면 각 검색 엔진의 HTML 구조에 맞게 크롤링 로직을 수정해야 합니다.
-
크롤링 속도 및 딜레이 조절:
delay 함수의 시간을 사용자 입력에 따라 동적으로 조절할 수 있도록 하면 유용합니다.
-
에러 핸들링 강화:
- 네트워크 오류나 DOM 변경으로 인한 오류를 처리하는 로직을 추가하여 크롤링의 안정성을 높일 수 있습니다.
-
사용자 교육 자료 제공:
- 스크립트를 사용하는 아이들을 위해 간단한 사용 방법과 주의사항을 문서화하여 제공하면 학습에 도움이 됩니다.
마무리
위의 스크립트와 설명을 바탕으로 기본적인 웹 크롤링 기능을 구현할 수 있습니다. 교육적인 목적에 맞게 추가 기능을 확장하고, 필요한 경우 사용자 인터페이스를 더욱 친화적으로 개선할 수 있습니다. Tampermonkey를 활용한 웹 크롤링은 브라우저 내에서 간단하게 자동화 작업을 수행할 수 있는 강력한 도구이므로, 다양한 실습을 통해 학습 효과를 극대화할 수 있을 것입니다.
추가적인 질문이나 도움이 필요하시면 언제든지 말씀해 주세요!