javascript Copy code
// ==UserScript==
// @name 웹 크롤러 스크립트
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 검색 결과를 크롤링하여 엑셀 형태로 표시
// @author Your Name
// @match *://*/*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @connect *
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
// 스타일 추가
GM_addStyle(`
#crawler-ui {
position: fixed;
top: 10px;
right: 10px;
width: 300px;
background: #f9f9f9;
border: 1px solid #ccc;
padding: 10px;
z-index: 10000;
font-family: Arial, sans-serif;
}
#crawler-ui button {
width: 80px;
margin: 5px 2px;
}
#progress-bar {
width: 100%;
background: #ddd;
height: 20px;
margin-top: 10px;
position: relative;
}
#progress-fill {
background: #4caf50;
height: 100%;
width: 0%;
}
#result-table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
display: none;
}
#result-table th, #result-table td {
border: 1px solid #ccc;
padding: 5px;
text-align: left;
}
#result-table th {
background: #eee;
}
`);
// UI 생성
const ui = document.createElement('div');
ui.id = 'crawler-ui';
ui.innerHTML = `
<button id="start-btn">시작</button>
<button id="stop-btn">중지</button>
<button id="reset-btn">초기화</button>
<div id="progress-bar"><div id="progress-fill"></div></div>
<table id="result-table">
<thead>
<tr>
<th>사이트 이름</th>
<th>주소</th>
<th>설명</th>
</tr>
</thead>
<tbody></tbody>
</table>
`;
document.body.appendChild(ui);
// 변수 초기화
let isCrawling = false;
let results = [];
let totalPages = 0;
let currentPage = 1;
let totalResults = 0;
const startBtn = document.getElementById('start-btn');
const stopBtn = document.getElementById('stop-btn');
const resetBtn = document.getElementById('reset-btn');
const progressFill = document.getElementById('progress-fill');
const resultTable = document.getElementById('result-table').getElementsByTagName('tbody')[0];
// 버튼 이벤트
startBtn.addEventListener('click', startCrawling);
stopBtn.addEventListener('click', stopCrawling);
resetBtn.addEventListener('click', resetCrawling);
function startCrawling() {
if (isCrawling) return;
isCrawling = true;
results = [];
resultTable.innerHTML = '';
resultTable.parentElement.style.display = 'none';
// 검색어 가져오기 (검색창에서 입력된 값)
const searchInput = document.querySelector('input[type="text"], input[type="search"]');
if (!searchInput) {
alert('검색 입력창을 찾을 수 없습니다.');
isCrawling = false;
return;
}
const query = searchInput.value;
if (!query) {
alert('검색어를 입력해주세요.');
isCrawling = false;
return;
}
// 시작 크롤링
crawlPage(query, currentPage);
}
function stopCrawling() {
isCrawling = false;
}
function resetCrawling() {
isCrawling = false;
results = [];
currentPage = 1;
totalPages = 0;
totalResults = 0;
progressFill.style.width = '0%';
resultTable.innerHTML = '';
resultTable.parentElement.style.display = 'none';
}
function crawlPage(query, page) {
if (!isCrawling) return;
// 여기서 검색 엔진 URL을 설정합니다. 예: Google
const searchUrl = `https://www.bing.com/search?q=${encodeURIComponent(query)}&first=${(page-1)*10 +1}`;
GM_xmlhttpRequest({
method: "GET",
url: searchUrl,
onload: function(response) {
if (!isCrawling) return;
// 결과 파싱
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const items = doc.querySelectorAll('li.b_algo');
items.forEach(item => {
const title = item.querySelector('h2 a') ? item.querySelector('h2 a').innerText : 'N/A';
const link = item.querySelector('h2 a') ? item.querySelector('h2 a').href : 'N/A';
const desc = item.querySelector('.b_caption p') ? item.querySelector('.b_caption p').innerText : 'N/A';
results.push({ title, link, desc });
});
// 페이지 수 계산
if (page === 1) {
const pager = doc.querySelector('.sb_pagS') || doc.querySelector('.b_pag');
if (pager) {
const pages = pager.querySelectorAll('a');
totalPages = pages.length;
} else {
totalPages = 1;
}
}
// 진행률 업데이트
progressFill.style.width = `${((page) / totalPages) * 100}%`;
// 다음 페이지 크롤링
if (page < totalPages && isCrawling) {
currentPage++;
setTimeout(() => crawlPage(query, currentPage), 1000);
} else {
isCrawling = false;
displayResults();
}
},
onerror: function() {
alert('크롤링 중 오류가 발생했습니다.');
isCrawling = false;
}
});
}
function displayResults() {
if (results.length === 0) {
alert('검색 결과가 없습니다.');
return;
}
results.forEach(item => {
const row = document.createElement('tr');
const titleCell = document.createElement('td');
const linkCell = document.createElement('td');
const descCell = document.createElement('td');
titleCell.innerText = item.title;
const linkAnchor = document.createElement('a');
linkAnchor.href = item.link;
linkAnchor.innerText = item.link;
linkAnchor.target = '_blank';
linkCell.appendChild(linkAnchor);
descCell.innerText = item.desc;
row.appendChild(titleCell);
row.appendChild(linkCell);
row.appendChild(descCell);
resultTable.appendChild(row);
});
resultTable.parentElement.style.display = 'block';
}
})();