// 설정
const LAST_PAGE = 10; // 실제 마지막 페이지 번호로 변경
const DATA_KEY = 'crawledData';
const PAGE_KEY = 'currentPage';
// 데이터 저장 및 현재 페이지 번호 가져오기
let allData = JSON.parse(localStorage.getItem(DATA_KEY)) || [];
let currentPage = parseInt(localStorage.getItem(PAGE_KEY)) || 1; 안 되는뎅...? 수정해줘?
// 현재 페이지 번호 가져오기 (URL에서)
const urlParams = new URLSearchParams(window.location.search);
let pageFromURL = parseInt(urlParams.get('page')) || 1;
// 데이터가 이미 수집되었는지 확인
if (pageFromURL !== currentPage) {
currentPage = pageFromURL;
}
// 데이터 수집 함수 (실제 데이터에 맞게 수정)
function collectData() {
let items = document.querySelectorAll('.item-class'); // 각 항목을 선택하는 선택자
items.forEach(item => {
let title = item.querySelector('.title-class').innerText.trim();
let link = item.querySelector('a').href;
allData.push({ title, link });
});
}
// 진행 바 생성 함수
function createProgressBar() {
// 스타일 추가
const style = document.createElement('style');
style.innerHTML = `
#tampermonkey-progress-bar-container {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
width: 80%;
height: 25px;
background-color: #f3f3f3;
border: 1px solid #ccc;
border-radius: 5px;
z-index: 10000;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
#tampermonkey-progress-bar {
width: 0%;
height: 100%;
background-color: #4caf50;
border-radius: 5px;
transition: width 0.3s;
}
#tampermonkey-progress-text {
position: absolute;
width: 100%;
text-align: center;
line-height: 25px;
font-size: 14px;
color: #000;
font-weight: bold;
}
`;
document.head.appendChild(style);
// 컨테이너 생성
const container = document.createElement('div');
container.id = 'tampermonkey-progress-bar-container';
// 진행 바
const progressBar = document.createElement('div');
progressBar.id = 'tampermonkey-progress-bar';
// 진행 텍스트
const progressText = document.createElement('div');
progressText.id = 'tampermonkey-progress-text';
progressText.innerText = `Page ${currentPage} of ${LAST_PAGE}`;
// 구성 요소 추가
container.appendChild(progressBar);
container.appendChild(progressText);
document.body.appendChild(container);
// 진행 바 업데이트 함수
function updateProgressBar() {
const progressPercent = (currentPage / LAST_PAGE) * 100;
progressBar.style.width = `${progressPercent}%`;
progressText.innerText = `Page ${currentPage} of ${LAST_PAGE} (${progressPercent.toFixed(2)}%)`;
}
updateProgressBar();
}
// CSV 다운로드 함수
function downloadCSV(data) {
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Title,Link\r\n"; // 헤더
data.forEach(row => {
// 쉼표와 줄바꿈 처리
let title = `"${row.title.replace(/"/g, '""')}"`;
let link = `"${row.link}"`;
csvContent += `${title},${link}\r\n`;
});
let encodedUri = encodeURI(csvContent);
let linkElement = document.createElement("a");
linkElement.setAttribute("href", encodedUri);
linkElement.setAttribute("download", "crawled_data.csv");
document.body.appendChild(linkElement); // Firefox 호환성
linkElement.click();
document.body.removeChild(linkElement);
}
// 진행 바 생성
createProgressBar();
// 데이터 수집
collectData();
// 다음 페이지로 이동 또는 다운로드
if (currentPage < LAST_PAGE) {
// 진행 상태 저장
localStorage.setItem(DATA_KEY, JSON.stringify(allData));
localStorage.setItem(PAGE_KEY, currentPage + 1);
// 다음 페이지로 이동 (지연을 줘서 진행 바가 보이도록)
setTimeout(() => {
window.location.href = `https://www.example.com/list?page=${currentPage + 1}`;
}, 1000); // 1초 지연
} else {
// 마지막 페이지에서 데이터 저장 및 다운로드
localStorage.setItem(DATA_KEY, JSON.stringify(allData));
localStorage.removeItem(PAGE_KEY); // 페이지 번호 초기화
// 진행 바 업데이트
const progressBar = document.getElementById('tampermonkey-progress-bar');
const progressText = document.getElementById('tampermonkey-progress-text');
if (progressBar && progressText) {
progressBar.style.width = '100%';
progressText.innerText = `Crawling Complete! Downloading CSV...`;
}
// CSV 다운로드
downloadCSV(allData);
// 데이터 초기화
localStorage.removeItem(DATA_KEY);
}
// ==UserScript==
// @name 웹 크롤러 및 CSV 다운로드 with Progress Bar
// @namespace http://tampermonkey.net/
// @version 1.2
// @description 여러 페이지를 크롤링하고 진행 바를 표시한 후 데이터를 CSV로 다운로드
// @author Your Name
// @match https://www.google.com/search*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 설정
const LAST_PAGE = 10; // 실제 마지막 페이지 번호로 변경
const DATA_KEY = 'crawledData';
const PAGE_KEY = 'currentPage';
// 데이터 저장 및 현재 페이지 번호 가져오기
let allData = JSON.parse(localStorage.getItem(DATA_KEY)) || [];
let currentPage = parseInt(localStorage.getItem(PAGE_KEY)) || 1;
// 현재 페이지 번호 가져오기 (URL에서 start 파라미터 이용)
const urlParams = new URLSearchParams(window.location.search);
let startParam = parseInt(urlParams.get('start')) || 0;
let pageFromURL = Math.floor(startParam / 10) + 1; // Google 검색은 start=0이 첫 페이지
// 데이터가 이미 수집되었는지 확인
if (pageFromURL !== currentPage) {
currentPage = pageFromURL;
}
// 데이터 수집 함수 (실제 데이터에 맞게 수정)
function collectData() {
let items = document.querySelectorAll('.g'); // 각 검색 결과 항목 선택 (Google 기준)
items.forEach(item => {
let titleElement = item.querySelector('h3');
let linkElement = item.querySelector('a');
if (titleElement && linkElement) {
let title = titleElement.innerText.trim();
let link = linkElement.href;
allData.push({ title, link });
}
});
}
// 진행 바 생성 함수
function createProgressBar() {
// 이미 진행 바가 있는 경우 제거
const existingContainer = document.getElementById('tampermonkey-progress-bar-container');
if (existingContainer) return;
// 스타일 추가
const style = document.createElement('style');
style.innerHTML = `
#tampermonkey-progress-bar-container {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
width: 80%;
height: 25px;
background-color: #f3f3f3;
border: 1px solid #ccc;
border-radius: 5px;
z-index: 10000;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
#tampermonkey-progress-bar {
width: 0%;
height: 100%;
background-color: #4caf50;
border-radius: 5px;
transition: width 0.3s;
}
#tampermonkey-progress-text {
position: absolute;
width: 100%;
text-align: center;
line-height: 25px;
font-size: 14px;
color: #000;
font-weight: bold;
}
`;
document.head.appendChild(style);
// 컨테이너 생성
const container = document.createElement('div');
container.id = 'tampermonkey-progress-bar-container';
// 진행 바
const progressBar = document.createElement('div');
progressBar.id = 'tampermonkey-progress-bar';
// 진행 텍스트
const progressText = document.createElement('div');
progressText.id = 'tampermonkey-progress-text';
progressText.innerText = `Page ${currentPage} of ${LAST_PAGE}`;
// 구성 요소 추가
container.appendChild(progressBar);
container.appendChild(progressText);
document.body.appendChild(container);
// 진행 바 업데이트 함수
function updateProgressBar() {
const progressPercent = (currentPage / LAST_PAGE) * 100;
progressBar.style.width = `${progressPercent}%`;
progressText.innerText = `Page ${currentPage} of ${LAST_PAGE} (${progressPercent.toFixed(2)}%)`;
}
updateProgressBar();
}
// CSV 다운로드 함수
function downloadCSV(data) {
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Title,Link\r\n"; // 헤더
data.forEach(row => {
// 쉼표와 따옴표 처리
let title = `"${row.title.replace(/"/g, '""')}"`;
let link = `"${row.link.replace(/"/g, '""')}"`;
csvContent += `${title},${link}\r\n`;
});
let encodedUri = encodeURI(csvContent);
let linkElement = document.createElement("a");
linkElement.setAttribute("href", encodedUri);
linkElement.setAttribute("download", "crawled_data.csv");
document.body.appendChild(linkElement); // Firefox 호환성
linkElement.click();
document.body.removeChild(linkElement);
}
// 진행 바 생성
createProgressBar();
// 데이터 수집
collectData();
// 다음 페이지로 이동 또는 다운로드
if (currentPage < LAST_PAGE) {
// 진행 상태 저장
localStorage.setItem(DATA_KEY, JSON.stringify(allData));
localStorage.setItem(PAGE_KEY, currentPage + 1);
// 다음 페이지 이동을 위한 start 파라미터 계산
let nextStart = (currentPage) * 10; // Google 검색은 10개씩 표시
// 다음 페이지로 이동 (지연을 줘서 진행 바가 보이도록)
setTimeout(() => {
window.location.href = `https://www.google.com/search?q=${encodeURIComponent(urlParams.get('q') || '')}&start=${nextStart}`;
}, 1000); // 1초 지연
} else {
// 마지막 페이지에서 데이터 저장 및 다운로드
localStorage.setItem(DATA_KEY, JSON.stringify(allData));
localStorage.removeItem(PAGE_KEY); // 페이지 번호 초기화
// 진행 바 업데이트
const progressBar = document.getElementById('tampermonkey-progress-bar');
const progressText = document.getElementById('tampermonkey-progress-text');
if (progressBar && progressText) {
progressBar.style.width = '100%';
progressText.innerText = `Crawling Complete! Downloading CSV...`;
}
// CSV 다운로드
setTimeout(() => { // 업데이트 메시지를 보기 위해 약간의 지연 추가
downloadCSV(allData);
}, 2000);
// 데이터 초기화
localStorage.removeItem(DATA_KEY);
}
})();