// ==UserScript== // @name Advanced Web Crawler Enhanced // @namespace…
- User
// ==UserScript== // @name Advanced Web Crawler Enhanced // @namespace http://tampermonkey.net/ // @version 2.0 // @description 고급 웹 크롤러 스크립트 with Enhanced Settings and Features // @author Your Name // @match https://www.google.com/search* // @match https://www.bing.com/search* // @match https://search.yahoo.com/search* // @match https://duckduckgo.com/* // @match https://www.baidu.com/s* // @match https://www.yandex.com/search/* // @match https://search.naver.com/search* // @match https://search.daum.net/search* // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @connect * // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js // ==/UserScript==
(function() { 'use strict';
code// 기본 설정 const defaultSettings = { delay: 3000, // 기본 딜레이 3초 maxPages: 5, // 기본 최대 크롤링 페이지 수 userAgent: 'AdvancedWebCrawler/2.0', // 기본 사용자 에이전트 blacklist: [], whitelist: [], contentTypes: { include: ['text/html'], exclude: [] }, timeout: 10000, // 기본 타임아웃 10초 includeKeywords: [], excludeKeywords: [], language: [], // 언어 필터링 (예: ['en', 'ko']) minWordCount: 100, // 최소 단어 수 maxWordCount: 10000, // 최대 단어 수 maxDepth: 2, // 링크 추적 최대 깊이 proxy: '', // 프록시 서버 URL regexInclude: [], // 포함 키워드 정규 표현식 regexExclude: [], // 제외 키워드 정규 표현식 dataFields: { name: true, url: true, description: true, html: false, category: true, quality: true }, schedule: { enabled: false, startTime: '00:00', // 형식: 'HH:MM' interval: 3600000 // 밀리초 단위 (예: 1시간) }, searchEngines: { google: true, bing: true, yahoo: true, duckduckgo: true, baidu: true, yandex: true, naver: true, daum: true } }; const settings = { delay: parseInt(GM_getValue('delay', defaultSettings.delay), 10), maxPages: parseInt(GM_getValue('maxPages', defaultSettings.maxPages), 10), userAgent: GM_getValue('userAgent', defaultSettings.userAgent), blacklist: GM_getValue('blacklist', defaultSettings.blacklist), whitelist: GM_getValue('whitelist', defaultSettings.whitelist), contentTypes: GM_getValue('contentTypes', defaultSettings.contentTypes), timeout: parseInt(GM_getValue('timeout', defaultSettings.timeout), 10), includeKeywords: GM_getValue('includeKeywords', defaultSettings.includeKeywords), excludeKeywords: GM_getValue('excludeKeywords', defaultSettings.excludeKeywords), language: GM_getValue('language', defaultSettings.language), minWordCount: parseInt(GM_getValue('minWordCount', defaultSettings.minWordCount), 10), maxWordCount: parseInt(GM_getValue('maxWordCount', defaultSettings.maxWordCount), 10), maxDepth: parseInt(GM_getValue('maxDepth', defaultSettings.maxDepth), 10), proxy: GM_getValue('proxy', defaultSettings.proxy), regexInclude: GM_getValue('regexInclude', defaultSettings.regexInclude), regexExclude: GM_getValue('regexExclude', defaultSettings.regexExclude), dataFields: GM_getValue('dataFields', defaultSettings.dataFields), schedule: GM_getValue('schedule', defaultSettings.schedule), searchEngines: GM_getValue('searchEngines', defaultSettings.searchEngines) }; // 크롤링 상태 복원 let visitedUrls = GM_getValue('visitedUrls', []); let logs = GM_getValue('logs', []); let data = GM_getValue('data', []); let isCrawling = GM_getValue('isCrawling', false); let currentPage = GM_getValue('currentPage', 1); let totalPages = GM_getValue('totalPages', settings.maxPages); let progress = GM_getValue('progress', 0); let currentDepth = GM_getValue('currentDepth', 0); // UI 생성 function createUI() { const style = ` /* 스타일 추가 */ #crawler-container { position: fixed; top: 10px; right: 10px; width: 800px; height: 900px; background: #fff; border: 1px solid #ccc; z-index: 10000; font-family: Arial, sans-serif; box-shadow: 0 4px 8px rgba(0,0,0,0.2); overflow: hidden; } #crawler-tabs { display: flex; background: #f1f1f1; } .crawler-tab { flex: 1; padding: 10px; text-align: center; cursor: pointer; } .crawler-tab.active { background: #ddd; } #crawler-content { padding: 10px; overflow: auto; height: 780px; } /* 추가적인 스타일 */ table { width: 100%; border-collapse: collapse; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } th { background-color: #f2f2f2; } tr:hover { background-color: #f5f5f5; } .progress-bar { width: 100%; background-color: #f3f3f3; border: 1px solid #ccc; border-radius: 5px; overflow: hidden; margin-bottom: 10px; } .progress-bar-fill { height: 25px; background-color: #4caf50; width: 0%; transition: width 0.2s; } .modal { display: none; position: fixed; z-index: 10001; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); } .modal-content { background-color: #fff; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 80%; max-height: 80%; overflow-y: auto; } .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; } .control-buttons { margin: 10px 0; } .control-buttons button { padding: 10px 20px; margin-right: 10px; cursor: pointer; } .status-text { margin-top: 10px; font-weight: bold; } /* 설정 섹션 스타일 */ .settings-section { margin-bottom: 15px; } .settings-section label { display: block; margin-bottom: 5px; font-weight: bold; } .settings-section input[type="text"], .settings-section input[type="number"], .settings-section textarea, .settings-section select { width: 100%; padding: 5px; box-sizing: border-box; } .settings-section .checkbox-group { display: flex; flex-wrap: wrap; } .settings-section .checkbox-group label { margin-right: 10px; } .settings-section .radio-group { display: flex; flex-wrap: wrap; } .settings-section .radio-group label { margin-right: 10px; } `; $('head').append(`<style>${style}</style>`); const container = $(` <div id="crawler-container"> <div id="crawler-tabs"> <div class="crawler-tab ${currentTab() === 'logs' ? 'active' : ''}" data-tab="logs" title="로그 보기">📜 로그</div> <div class="crawler-tab ${currentTab() === 'data' ? 'active' : ''}" data-tab="data" title="수집된 데이터 보기">📊 데이터</div> <div class="crawler-tab ${currentTab() === 'settings' ? 'active' : ''}" data-tab="settings" title="설정 변경">⚙️ 설정</div> </div> <div id="crawler-content"> <div id="tab-logs" style="display: ${currentTab() === 'logs' ? 'block' : 'none'};"> <div class="progress-bar"> <div class="progress-bar-fill" style="width: ${progress.toFixed(2)}%;"></div> </div> <div class="status-text">진행률: ${progress.toFixed(2)}% (${currentPage}/${totalPages} 페이지)</div> <div class="control-buttons"> <button id="start-crawling" title="크롤링을 시작합니다." ${isCrawling ? 'disabled' : ''}>▶ 시작</button> <button id="stop-crawling" title="크롤링을 중지합니다." ${isCrawling ? '' : 'disabled'}>■ 중지</button> <button id="download-csv" title="수집된 데이터를 CSV 파일로 다운로드합니다.">📥 CSV 다운로드</button> <button id="download-json" title="수집된 데이터를 JSON 파일로 다운로드합니다.">📥 JSON 다운로드</button> </div> <div id="log-messages" style="height: 400px; overflow-y: auto;">로그 내용이 여기에 표시됩니다.</div> </div> <div id="tab-data" style="display: ${currentTab() === 'data' ? 'block' : 'none'};"> <input type="text" id="search-filter" placeholder="검색 필터..." title="데이터 필터링을 위한 키워드를 입력하세요." style="width: 100%; padding: 5px; margin-bottom: 10px;"> <table> <thead> <tr> <th>사이트 이름</th> <th>주소</th> <th>설명</th> <th>HTML</th> <th>분류</th> <th>품질</th> </tr> </thead> <tbody id="data-table-body"> <!-- 데이터 행이 여기에 추가됩니다. --> </tbody> </table> </div> <div id="tab-settings" style="display: ${currentTab() === 'settings' ? 'block' : 'none'};"> <h3>설정</h3> <!-- 크롤링 설정 섹션 --> <div class="settings-section"> <label for="delay-input">크롤링 딜레이 (ms):</label> <input type="number" id="delay-input" value="${settings.delay}" title="크롤링 요청 사이의 딜레이를 밀리초 단위로 설정하세요." min="500" step="500"> </div> <div class="settings-section"> <label for="max-pages-input">최대 크롤링 페이지 수:</label> <input type="number" id="max-pages-input" value="${settings.maxPages}" title="크롤링할 최대 페이지 수를 설정하세요." min="1"> </div> <div class="settings-section"> <label for="user-agent-input">사용자 에이전트(User-Agent):</label> <input type="text" id="user-agent-input" value="${settings.userAgent}" title="크롤링에 사용할 사용자 에이전트를 입력하세요."> </div> <!-- 콘텐츠 유형 섹션 --> <div class="settings-section"> <label>콘텐츠 유형:</label> <div> <strong>포함할 유형:</strong> <textarea id="content-include-input" rows="3" title="크롤링할 콘텐츠 유형을 입력하세요. 각 유형은 쉼표로 구분됩니다. 예: text/html, application/json">${settings.contentTypes.include.join(', ')}</textarea> </div> <div> <strong>제외할 유형:</strong> <textarea id="content-exclude-input" rows="3" title="크롤링에서 제외할 콘텐츠 유형을 입력하세요. 각 유형은 쉼표로 구분됩니다. 예: image/jpeg, video/mp4">${settings.contentTypes.exclude.join(', ')}</textarea> </div> </div> <!-- 타임아웃 섹션 --> <div class="settings-section"> <label for="timeout-input">크롤링 타임아웃 (ms):</label> <input type="number" id="timeout-input" value="${settings.timeout}" title="크롤링 요청의 타임아웃을 밀리초 단위로 설정하세요." min="1000" step="1000"> </div> <!-- 키워드 섹션 --> <div class="settings-section"> <label for="include-keywords-input">포함할 키워드:</label> <textarea id="include-keywords-input" rows="3" style="width: 100%;" title="크롤링할 페이지에 반드시 포함되어야 하는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.">${settings.includeKeywords.join('\n')}</textarea> </div> <div class="settings-section"> <label for="exclude-keywords-input">제외할 키워드:</label> <textarea id="exclude-keywords-input" rows="3" style="width: 100%;" title="크롤링할 페이지에 포함되면 안 되는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.">${settings.excludeKeywords.join('\n')}</textarea> </div> <!-- 정규 표현식 키워드 섹션 --> <div class="settings-section"> <label for="regex-include-input">포함할 키워드 (정규 표현식):</label> <textarea id="regex-include-input" rows="3" style="width: 100%;" title="포함할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.">${settings.regexInclude.join('\n')}</textarea> </div> <div class="settings-section"> <label for="regex-exclude-input">제외할 키워드 (정규 표현식):</label> <textarea id="regex-exclude-input" rows="3" style="width: 100%;" title="제외할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.">${settings.regexExclude.join('\n')}</textarea> </div> <!-- 언어 필터링 섹션 --> <div class="settings-section"> <label for="language-select">언어 필터링:</label> <select id="language-select" multiple size="5" title="크롤링할 언어를 선택하세요. 선택하지 않으면 모든 언어가 포함됩니다."> <option value="en" ${settings.language.includes('en') ? 'selected' : ''}>영어 (en)</option> <option value="ko" ${settings.language.includes('ko') ? 'selected' : ''}>한국어 (ko)</option> <option value="zh" ${settings.language.includes('zh') ? 'selected' : ''}>중국어 (zh)</option> <option value="ja" ${settings.language.includes('ja') ? 'selected' : ''}>일본어 (ja)</option> <option value="ru" ${settings.language.includes('ru') ? 'selected' : ''}>러시아어 (ru)</option> <!-- 추가 언어 옵션 --> </select> </div> <!-- 단어 수 섹션 --> <div class="settings-section"> <label for="min-word-count-input">최소 단어 수:</label> <input type="number" id="min-word-count-input" value="${settings.minWordCount}" title="수집할 페이지의 최소 단어 수를 설정하세요." min="10" step="10"> </div> <div class="settings-section"> <label for="max-word-count-input">최대 단어 수:</label> <input type="number" id="max-word-count-input" value="${settings.maxWordCount}" title="수집할 페이지의 최대 단어 수를 설정하세요." min="100" step="100"> </div> <!-- 심층 크롤링 섹션 --> <div class="settings-section"> <label for="max-depth-input">최대 크롤링 깊이:</label> <input type="number" id="max-depth-input" value="${settings.maxDepth}" title="링크를 추적할 최대 깊이를 설정하세요." min="1" step="1"> </div> <!-- 프록시 섹션 --> <div class="settings-section"> <label for="proxy-input">프록시 서버:</label> <input type="text" id="proxy-input" value="${settings.proxy}" placeholder="http://proxyserver:port" title="프록시 서버 주소를 입력하세요. (옵션)"> </div> <!-- 데이터 필드 섹션 --> <div class="settings-section"> <label>수집할 데이터 필드:</label> <div class="checkbox-group"> <label><input type="checkbox" id="field-name" ${settings.dataFields.name ? 'checked' : ''}> 사이트 이름</label> <label><input type="checkbox" id="field-url" ${settings.dataFields.url ? 'checked' : ''}> 주소</label> <label><input type="checkbox" id="field-description" ${settings.dataFields.description ? 'checked' : ''}> 설명</label> <label><input type="checkbox" id="field-html" ${settings.dataFields.html ? 'checked' : ''}> HTML</label> <label><input type="checkbox" id="field-category" ${settings.dataFields.category ? 'checked' : ''}> 분류</label> <label><input type="checkbox" id="field-quality" ${settings.dataFields.quality ? 'checked' : ''}> 품질점수</label> </div> </div> <!-- 스케줄링 섹션 --> <div class="settings-section"> <label>크롤링 스케줄링:</label> <div class="checkbox-group"> <label><input type="checkbox" id="schedule-enabled" ${settings.schedule.enabled ? 'checked' : ''} title="크롤링 작업을 예약하려면 체크하세요."> 스케줄링 활성화</label> </div> <div id="schedule-options" style="display: ${settings.schedule.enabled ? 'block' : 'none'}; margin-top: 10px;"> <label for="start-time-input">시작 시간 (HH:MM):</label> <input type="time" id="start-time-input" value="${settings.schedule.startTime}" title="크롤링을 시작할 시간을 설정하세요."> <label for="interval-input">크롤링 간격 (밀리초):</label> <input type="number" id="interval-input" value="${settings.schedule.interval}" title="크롤링 작업 간의 간격을 밀리초 단위로 설정하세요." min="60000" step="60000"> </div> </div> <!-- 검색 엔진 선택 섹션 --> <div class="settings-section"> <label>크롤링할 검색 엔진 선택:</label> <div class="checkbox-group"> <label><input type="checkbox" id="engine-google" ${settings.searchEngines.google ? 'checked' : ''}> Google</label> <label><input type="checkbox" id="engine-bing" ${settings.searchEngines.bing ? 'checked' : ''}> Bing</label> <label><input type="checkbox" id="engine-yahoo" ${settings.searchEngines.yahoo ? 'checked' : ''}> Yahoo</label> <label><input type="checkbox" id="engine-duckduckgo" ${settings.searchEngines.duckduckgo ? 'checked' : ''}> DuckDuckGo</label> <label><input type="checkbox" id="engine-baidu" ${settings.searchEngines.baidu ? 'checked' : ''}> Baidu</label> <label><input type="checkbox" id="engine-yandex" ${settings.searchEngines.yandex ? 'checked' : ''}> Yandex</label> <label><input type="checkbox" id="engine-naver" ${settings.searchEngines.naver ? 'checked' : ''}> Naver</label> <label><input type="checkbox" id="engine-daum" ${settings.searchEngines.daum ? 'checked' : ''}> Daum</label> </div> </div> <!-- 블랙리스트/화이트리스트 섹션 --> <div class="settings-section"> <label for="blacklist-input">블랙리스트 도메인:</label> <textarea id="blacklist-input" rows="5" style="width: 100%;" title="크롤링에서 제외할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.">${settings.blacklist.join('\n')}</textarea> </div> <div class="settings-section"> <label for="whitelist-input">화이트리스트 도메인:</label> <textarea id="whitelist-input" rows="5" style="width: 100%;" title="크롤링을 허용할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.">${settings.whitelist.join('\n')}</textarea> </div> <button id="save-settings" title="설정을 저장합니다." style="margin-top: 10px; padding: 5px 10px;">저장</button> </div> </div> <!-- 모달 창 --> <div id="html-modal" class="modal"> <div class="modal-content"> <span class="close">×</span> <pre id="modal-html-content" style="white-space: pre-wrap;"></pre> </div> </div> `); $('body').append(container); // 탭 전환 이벤트 $('.crawler-tab').on('click', function() { const tab = $(this).data('tab'); $('.crawler-tab').removeClass('active'); $(this).addClass('active'); $('#crawler-content > div').hide(); $(`#tab-${tab}`).show(); saveCurrentTab(tab); }); // 단축키 이벤트 $(document).on('keydown', function(e) { if (e.ctrlKey) { switch (e.key) { case '1': $('.crawler-tab[data-tab="logs"]').click(); break; case '2': $('.crawler-tab[data-tab="data"]').click(); break; case '3': $('.crawler-tab[data-tab="settings"]').click(); break; case 's': e.preventDefault(); saveSettings(); break; case 'p': e.preventDefault(); if (!isCrawling) startCrawling(); break; case 'q': e.preventDefault(); if (isCrawling) stopCrawling(); break; case 'd': e.preventDefault(); downloadCSV(); break; case 'j': e.preventDefault(); downloadJSON(); break; } } }); // 설정 저장 버튼 이벤트 $('#save-settings').on('click', saveSettings); // 다운로드 버튼 이벤트 $('#download-csv').on('click', downloadCSV); $('#download-json').on('click', downloadJSON); // 검색 필터 기능 $('#search-filter').on('input', function() { filterTable($(this).val()); }); // 스케줄링 옵션 표시/숨기기 $('#schedule-enabled').on('change', function() { if ($(this).is(':checked')) { $('#schedule-options').show(); } else { $('#schedule-options').hide(); } }); // 모달 창 기능 const modal = document.getElementById("html-modal"); const span = document.getElementsByClassName("close")[0]; span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } // 시작 및 중지 버튼 이벤트 $('#start-crawling').on('click', startCrawling); $('#stop-crawling').on('click', stopCrawling); // 초기 UI 업데이트 updateLogsUI(); updateDataUI(); } function currentTab() { return GM_getValue('currentTab', 'logs'); } function saveCurrentTab(tab) { GM_setValue('currentTab', tab); } // 로깅 함수 function log(message, type = 'info') { const timestamp = new Date().toLocaleString(); logs.push({ timestamp, message, type }); GM_setValue('logs', logs); updateLogsUI(); // type을 콘솔 메서드로 매핑 switch(type) { case 'info': console.info(`[${timestamp}] [INFO] ${message}`); break; case 'warning': console.warn(`[${timestamp}] [WARNING] ${message}`); break; case 'error': console.error(`[${timestamp}] [ERROR] ${message}`); break; case 'success': console.log(`%c[${timestamp}] [SUCCESS] ${message}`, 'color: green; font-weight: bold;'); break; default: console.log(`[${timestamp}] [${type.toUpperCase()}] ${message}`); } } function updateLogsUI() { const logHtml = logs.map(log => `<div>[${log.timestamp}] [${log.type.toUpperCase()}] ${log.message}</div>`).join(''); $('#log-messages').html(logHtml); $('.progress-bar-fill').css('width', `${progress.toFixed(2)}%`); $('.status-text').text(`진행률: ${progress.toFixed(2)}% (${currentPage}/${totalPages} 페이지)`); } // 데이터 업데이트 함수 function updateDataUI() { const filter = $('#search-filter').val().toLowerCase(); let filteredData = data; if (filter) { filteredData = data.filter(item => item.name.toLowerCase().includes(filter) || item.url.toLowerCase().includes(filter) || item.description.toLowerCase().includes(filter) || item.category.toLowerCase().includes(filter) ); } let tableHtml = filteredData.map(item => ` <tr> ${settings.dataFields.name ? `<td>${escapeHTML(item.name)}</td>` : ''} ${settings.dataFields.url ? `<td><a href="${escapeHTML(item.url)}" target="_blank">${escapeHTML(item.url)}</a></td>` : ''} ${settings.dataFields.description ? `<td>${escapeHTML(item.description)}</td>` : ''} ${settings.dataFields.html ? `<td><button class="view-html" data-html="${encodeURIComponent(item.html)}" title="HTML 내용을 봅니다.">보기</button></td>` : ''} ${settings.dataFields.category ? `<td>${escapeHTML(item.category)}</td>` : ''} ${settings.dataFields.quality ? `<td>${escapeHTML(item.quality.toString())}</td>` : ''} </tr> `).join(''); $('#data-table-body').html(tableHtml); // HTML 보기 모달 $('.view-html').off('click').on('click', function() { const htmlContent = decodeURIComponent($(this).data('html')); $('#modal-html-content').text(htmlContent); $('#html-modal').show(); }); } // HTML 이스케이프 함수 function escapeHTML(str) { if (!str) return ''; return str.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // 설정 저장 함수 function saveSettings() { const delay = parseInt($('#delay-input').val(), 10); settings.delay = isNaN(delay) ? defaultSettings.delay : delay; const maxPages = parseInt($('#max-pages-input').val(), 10); settings.maxPages = isNaN(maxPages) ? defaultSettings.maxPages : maxPages; const userAgent = $('#user-agent-input').val().trim(); settings.userAgent = userAgent || defaultSettings.userAgent; const contentInclude = $('#content-include-input').val().split(',').map(ct => ct.trim()).filter(ct => ct); const contentExclude = $('#content-exclude-input').val().split(',').map(ct => ct.trim()).filter(ct => ct); settings.contentTypes.include = contentInclude.length > 0 ? contentInclude : defaultSettings.contentTypes.include; settings.contentTypes.exclude = contentExclude.length > 0 ? contentExclude : defaultSettings.contentTypes.exclude; const timeout = parseInt($('#timeout-input').val(), 10); settings.timeout = isNaN(timeout) ? defaultSettings.timeout : timeout; const includeKeywords = $('#include-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw); settings.includeKeywords = includeKeywords; const excludeKeywords = $('#exclude-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw); settings.excludeKeywords = excludeKeywords; const regexInclude = $('#regex-include-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx); settings.regexInclude = regexInclude; const regexExclude = $('#regex-exclude-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx); settings.regexExclude = regexExclude; const language = $('#language-select').val() || []; settings.language = language; const minWordCount = parseInt($('#min-word-count-input').val(), 10); settings.minWordCount = isNaN(minWordCount) ? defaultSettings.minWordCount : minWordCount; const maxWordCount = parseInt($('#max-word-count-input').val(), 10); settings.maxWordCount = isNaN(maxWordCount) ? defaultSettings.maxWordCount : maxWordCount; const maxDepth = parseInt($('#max-depth-input').val(), 10); settings.maxDepth = isNaN(maxDepth) ? defaultSettings.maxDepth : maxDepth; const proxy = $('#proxy-input').val().trim(); settings.proxy = proxy || defaultSettings.proxy; // 데이터 필드 설정 settings.dataFields.name = $('#field-name').is(':checked'); settings.dataFields.url = $('#field-url').is(':checked'); settings.dataFields.description = $('#field-description').is(':checked'); settings.dataFields.html = $('#field-html').is(':checked'); settings.dataFields.category = $('#field-category').is(':checked'); settings.dataFields.quality = $('#field-quality').is(':checked'); // 스케줄링 설정 settings.schedule.enabled = $('#schedule-enabled').is(':checked'); const startTime = $('#start-time-input').val(); settings.schedule.startTime = startTime || defaultSettings.schedule.startTime; const interval = parseInt($('#interval-input').val(), 10); settings.schedule.interval = isNaN(interval) ? defaultSettings.schedule.interval : interval; const searchEngines = { google: $('#engine-google').is(':checked'), bing: $('#engine-bing').is(':checked'), yahoo: $('#engine-yahoo').is(':checked'), duckduckgo: $('#engine-duckduckgo').is(':checked'), baidu: $('#engine-baidu').is(':checked'), yandex: $('#engine-yandex').is(':checked'), naver: $('#engine-naver').is(':checked'), daum: $('#engine-daum').is(':checked') }; settings.searchEngines = searchEngines; const blacklist = $('#blacklist-input').val().split('\n').map(d => d.trim()).filter(d => d); settings.blacklist = blacklist; const whitelist = $('#whitelist-input').val().split('\n').map(d => d.trim()).filter(d => d); settings.whitelist = whitelist; // 저장 GM_setValue('delay', settings.delay); GM_setValue('maxPages', settings.maxPages); GM_setValue('userAgent', settings.userAgent); GM_setValue('contentTypes', settings.contentTypes); GM_setValue('timeout', settings.timeout); GM_setValue('includeKeywords', settings.includeKeywords); GM_setValue('excludeKeywords', settings.excludeKeywords); GM_setValue('regexInclude', settings.regexInclude); GM_setValue('regexExclude', settings.regexExclude); GM_setValue('language', settings.language); GM_setValue('minWordCount', settings.minWordCount); GM_setValue('maxWordCount', settings.maxWordCount); GM_setValue('maxDepth', settings.maxDepth); GM_setValue('proxy', settings.proxy); GM_setValue('dataFields', settings.dataFields); GM_setValue('schedule', settings.schedule); GM_setValue('searchEngines', settings.searchEngines); GM_setValue('blacklist', settings.blacklist); GM_setValue('whitelist', settings.whitelist); // totalPages 갱신 totalPages = settings.maxPages; GM_setValue('totalPages', totalPages); log('설정이 저장되었습니다.', 'success'); // 스케줄링 설정이 활성화된 경우 스케줄링 시작 if (settings.schedule.enabled) { scheduleCrawling(); } } // 크롤링 시작 함수 async function startCrawling() { if (isCrawling) { log('이미 크롤링이 진행 중입니다.', 'warning'); return; } // 활성화된 검색 엔진 확인 if (!isAnySearchEngineEnabled()) { log('사용할 검색 엔진이 하나도 선택되지 않았습니다.', 'error'); return; } isCrawling = true; GM_setValue('isCrawling', isCrawling); log('크롤링을 시작합니다.', 'info'); setButtonStates(); currentPage = GM_getValue('currentPage', 1); totalPages = GM_getValue('totalPages', settings.maxPages); GM_setValue('totalPages', totalPages); currentDepth = GM_getValue('currentDepth', 0); await crawlPage(currentDepth); } // 크롤링 중지 함수 function stopCrawling() { if (!isCrawling) { log('크롤링이 진행 중이지 않습니다.', 'warning'); return; } isCrawling = false; GM_setValue('isCrawling', isCrawling); log('크롤링이 중지되었습니다.', 'warning'); setButtonStates(); } // 버튼 상태 설정 함수 function setButtonStates() { if (isCrawling) { $('#start-crawling').prop('disabled', true); $('#stop-crawling').prop('disabled', false); } else { $('#start-crawling').prop('disabled', false); $('#stop-crawling').prop('disabled', true); } } // 크롤링 함수 async function crawlPage(currentDepth) { try { while (isCrawling && currentPage <= totalPages && currentDepth <= settings.maxDepth) { log(`페이지 ${currentPage} 크롤링 시작. (깊이: ${currentDepth})`, 'info'); const searchResults = extractSearchResults(); if (!searchResults) { log('검색 결과를 찾을 수 없습니다.', 'error'); break; } for (let result of searchResults) { if (!isCrawling) break; const name = result.name; const link = result.url; const description = result.description; // 중복 검사 if (visitedUrls.includes(link)) { log(`중복된 URL 발견: ${link}`, 'warning'); continue; } // 블랙리스트/화이트리스트 검사 if (settings.whitelist.length > 0 && !settings.whitelist.some(domain => link.includes(domain))) { log(`화이트리스트에 없는 도메인: ${link}`, 'warning'); continue; } if (settings.blacklist.some(domain => link.includes(domain))) { log(`블랙리스트에 있는 도메인: ${link}`, 'warning'); continue; } // 언어 필터링 검사 if (settings.language.length > 0) { const pageLanguage = await getPageLanguage(link); if (!settings.language.includes(pageLanguage)) { log(`선택된 언어에 맞지 않는 페이지: ${link} (${pageLanguage})`, 'warning'); continue; } } // 키워드 포함/제외 검사 if (settings.includeKeywords.length > 0 && !settings.includeKeywords.some(kw => link.includes(kw) || description.includes(kw))) { log(`포함 키워드가 없는 URL: ${link}`, 'warning'); continue; } if (settings.excludeKeywords.some(kw => link.includes(kw) || description.includes(kw))) { log(`제외 키워드가 포함된 URL: ${link}`, 'warning'); continue; } // 정규 표현식 필터링 if (settings.regexInclude.length > 0) { const matchesInclude = settings.regexInclude.some(pattern => new RegExp(pattern).test(link) || new RegExp(pattern).test(description)); if (!matchesInclude) { log(`정규 표현식 포함 조건에 맞지 않는 URL: ${link}`, 'warning'); continue; } } if (settings.regexExclude.length > 0) { const matchesExclude = settings.regexExclude.some(pattern => new RegExp(pattern).test(link) || new RegExp(pattern).test(description)); if (matchesExclude) { log(`정규 표현식 제외 조건에 맞는 URL: ${link}`, 'warning'); continue; } } // 데이터 수집 try { const response = await GM_xmlhttpRequestPromise(link); const contentType = getContentType(response); if (!isContentTypeAllowed(contentType)) { log(`허용되지 않은 콘텐츠 유형(${contentType})의 URL: ${link}`, 'warning'); continue; } const pageHtml = response.responseText; const parser = new DOMParser(); const pageDoc = parser.parseFromString(pageHtml, 'text/html'); const textContent = pageDoc.body ? pageDoc.body.innerText : ''; // 단어 수 검사 const wordCount = textContent.split(/\s+/).length; if (wordCount < settings.minWordCount) { log(`단어 수가 최소 기준 (${settings.minWordCount})에 미치지 못하는 URL: ${link} (${wordCount} 단어)`, 'warning'); continue; } if (wordCount > settings.maxWordCount) { log(`단어 수가 최대 기준 (${settings.maxWordCount})을 초과하는 URL: ${link} (${wordCount} 단어)`, 'warning'); continue; } // 콘텐츠 품질 평가 const qualityScore = evaluateContentQuality(textContent); // 키워드 분류 const category = classifyKeywords(textContent); // 조건에 맞는 경우에만 데이터 추가 if (category !== '기타' || qualityScore > 100) { // 예시 조건 const dataEntry = {}; if (settings.dataFields.name) dataEntry.name = name; if (settings.dataFields.url) dataEntry.url = link; if (settings.dataFields.description) dataEntry.description = description; if (settings.dataFields.html) dataEntry.html = pageHtml; if (settings.dataFields.category) dataEntry.category = category; if (settings.dataFields.quality) dataEntry.quality = qualityScore; data.push(dataEntry); GM_setValue('data', data); updateDataUI(); log(`데이터 수집 완료: ${link}`, 'success'); } else { log(`조건에 맞지 않아 데이터에 추가되지 않은 URL: ${link}`, 'info'); } // 링크 추적을 위한 추가 로직 (심층 크롤링) if (currentDepth < settings.maxDepth) { const additionalLinks = extractLinks(pageDoc); for (let additionalLink of additionalLinks) { if (!visitedUrls.includes(additionalLink) && isValidURL(additionalLink)) { // 큐에 추가하거나 다른 방식으로 심층 크롤링을 구현할 수 있음 // 여기서는 간단히 방문한 URL로 추가 visitedUrls.push(additionalLink); } } } } catch (error) { log(`데이터 수집 실패: ${link} - ${error.message}`, 'error'); // 실패한 경우 data에 추가하지 않음 } visitedUrls.push(link); GM_setValue('visitedUrls', visitedUrls); } // 진행률 업데이트 progress = (currentPage / totalPages) * 100; GM_setValue('progress', progress); updateLogsUI(); // 다음 페이지로 이동 if (currentPage < totalPages && isCrawling) { const nextPageUrl = getNextPageUrl(); if (nextPageUrl) { currentPage++; GM_setValue('currentPage', currentPage); currentDepth++; GM_setValue('currentDepth', currentDepth); log(`다음 페이지로 이동: ${currentPage}`, 'info'); await delay(settings.delay); window.location.href = nextPageUrl; return; // 페이지 이동 후 크롤링 이어서 하기 위해 함수 종료 } else { log('다음 페이지 링크를 찾을 수 없습니다.', 'error'); break; } } else { break; } } if (isCrawling && currentPage > totalPages) { log('크롤링이 완료되었습니다.', 'success'); isCrawling = false; GM_setValue('isCrawling', isCrawling); setButtonStates(); GM_setValue('progress', 100); $('.progress-bar-fill').css('width', `100%`); $('.status-text').text(`진행률: 100% (${currentPage}/${totalPages} 페이지)`); } } catch (error) { log(`크롤링 중 오류 발생: ${error.message}`, 'error'); } finally { // 크롤링이 아직 진행 중인 경우 state를 유지 if (!isCrawling) { // 크롤링이 중지된 경우에만 상태를 초기화 GM_setValue('isCrawling', isCrawling); setButtonStates(); log('크롤링이 중지되었습니다.', 'info'); } // 페이지 이동 시에는 상태를 유지하고, 다음 페이지에서 계속 크롤링 } } // 활성화된 검색 엔진이 있는지 확인 function isAnySearchEngineEnabled() { return Object.values(settings.searchEngines).some(enabled => enabled); } // 검색 결과 추출 함수 (각 검색 엔진에 맞게 수정됨) function extractSearchResults() { let results = []; // 구글 검색 결과 추출 (업데이트된 셀렉터) if (window.location.hostname.includes('google.com') && settings.searchEngines.google) { const items = document.querySelectorAll('div.g, div[data-hveid]'); items.forEach(item => { const nameElement = item.querySelector('h3'); const linkElement = item.querySelector('a'); let descElement = item.querySelector('.aCOpRe'); // 기존 셀렉터 if (!descElement) { descElement = item.querySelector('.VwiC3b'); // 대체 셀렉터 } const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 빙 검색 결과 추출 (업데이트된 셀렉터) else if (window.location.hostname.includes('bing.com') && settings.searchEngines.bing) { const items = document.querySelectorAll('.b_algo'); items.forEach(item => { const nameElement = item.querySelector('h2'); const linkElement = nameElement ? nameElement.querySelector('a') : null; const descElement = item.querySelector('.b_caption p'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 야후 검색 결과 추출 (업데이트된 셀렉터) else if (window.location.hostname.includes('search.yahoo.com') && settings.searchEngines.yahoo) { const items = document.querySelectorAll('div.dd.algo'); items.forEach(item => { const nameElement = item.querySelector('h3.title'); const linkElement = nameElement ? nameElement.querySelector('a') : null; const descElement = item.querySelector('.compText p'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 네이버 검색 결과 추출 (업데이트된 셀렉터) else if (window.location.hostname.includes('naver.com') && settings.searchEngines.naver) { const items = document.querySelectorAll('.news.mynews.section._prs_nws'); items.forEach(item => { const nameElement = item.querySelector('.news_area .news_tit'); const linkElement = nameElement ? nameElement.href : ''; const descElement = item.querySelector('.dsc_wrap'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 다음 검색 결과 추출 (업데이트된 셀렉터) else if (window.location.hostname.includes('daum.net') && settings.searchEngines.daum) { const items = document.querySelectorAll('.wrap_cont div'); items.forEach(item => { const nameElement = item.querySelector('a.f_link_b'); const linkElement = nameElement ? nameElement.href : ''; const descElement = item.querySelector('.desc'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 드도록 검색 결과 추출 (업데이트된 셀렉터) else if (window.location.hostname.includes('duckduckgo.com') && settings.searchEngines.duckduckgo) { const items = document.querySelectorAll('.result'); items.forEach(item => { const nameElement = item.querySelector('h2 a.result__a'); const linkElement = nameElement ? nameElement.href : ''; const descElement = item.querySelector('.result__snippet'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Baidu 검색 결과 추출 (예시) else if (window.location.hostname.includes('baidu.com') && settings.searchEngines.baidu) { const items = document.querySelectorAll('.result'); items.forEach(item => { const nameElement = item.querySelector('h3 a'); const linkElement = nameElement ? nameElement.href : ''; const descElement = item.querySelector('.c-abstract'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Yandex 검색 결과 추출 (예시) else if (window.location.hostname.includes('yandex.com') && settings.searchEngines.yandex) { const items = document.querySelectorAll('.serp-item'); items.forEach(item => { const nameElement = item.querySelector('.organic__title-link'); const linkElement = nameElement ? nameElement.href : ''; const descElement = item.querySelector('.text-container'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // 기타 검색 엔진에 대한 추가 로직 필요 else { log('지원되지 않거나 비활성화된 검색 엔진입니다.', 'warning'); } return results.length > 0 ? results : null; } // 다음 페이지 URL 얻는 함수 (각 검색 엔진에 맞게 수정됨) function getNextPageUrl() { let nextPageUrl = null; // 구글 다음 페이지 링크 if (window.location.hostname.includes('google.com') && settings.searchEngines.google) { const nextLink = document.querySelector('a#pnnext'); if (nextLink) nextPageUrl = nextLink.href; } // 빙 다음 페이지 링크 else if (window.location.hostname.includes('bing.com') && settings.searchEngines.bing) { const nextLink = document.querySelector('a.sb_pagN'); if (nextLink) nextPageUrl = nextLink.href; } // 야후 다음 페이지 링크 else if (window.location.hostname.includes('search.yahoo.com') && settings.searchEngines.yahoo) { const nextLink = document.querySelector('a.next'); if (nextLink) nextPageUrl = nextLink.href; } // 네이버 다음 페이지 링크 else if (window.location.hostname.includes('naver.com') && settings.searchEngines.naver) { const nextLink = document.querySelector('.sc_page_inner a.btn_next'); if (nextLink) nextPageUrl = nextLink.href; } // 다음 다음 페이지 링크 else if (window.location.hostname.includes('daum.net') && settings.searchEngines.daum) { const nextLink = document.querySelector('.paging a.btn_next'); if (nextLink) nextPageUrl = nextLink.href; } // 드도록 다음 페이지 링크 else if (window.location.hostname.includes('duckduckgo.com') && settings.searchEngines.duckduckgo) { const nextLink = document.querySelector('a.js-next-page'); if (nextLink) nextPageUrl = nextLink.href; } // Baidu 다음 페이지 링크 (예시) else if (window.location.hostname.includes('baidu.com') && settings.searchEngines.baidu) { const nextLink = document.querySelector('.n'); if (nextLink) nextPageUrl = nextLink.href; } // Yandex 다음 페이지 링크 (예시) else if (window.location.hostname.includes('yandex.com') && settings.searchEngines.yandex) { const nextLink = document.querySelector('.pager__item_kind_next a'); if (nextLink) nextPageUrl = nextLink.href; } // 기타 검색 엔진에 대한 추가 로직 필요 log(`다음 페이지 URL: ${nextPageUrl || '없음'}`, 'info'); return nextPageUrl; } // GM_xmlhttpRequest를 Promise로 래핑 function GM_xmlhttpRequestPromise(url) { return new Promise((resolve, reject) => { let requestUrl = url; if (settings.proxy) { // 프록시 요청을 위한 URL 구성 requestUrl = `${settings.proxy}?url=${encodeURIComponent(url)}`; } GM_xmlhttpRequest({ method: "GET", url: requestUrl, headers: { 'User-Agent': settings.userAgent }, timeout: settings.timeout, onload: function(response) { if (response.status >= 200 && response.status < 300) { resolve(response); } else { reject(new Error(`HTTP Status ${response.status}`)); } }, onerror: function(error) { reject(error); }, ontimeout: function() { reject(new Error('Request timed out')); } }); }); } // 콘텐츠 유형 얻는 함수 function getContentType(response) { const contentType = response.responseHeaders.split('\n').find(header => header.toLowerCase().startsWith('content-type')); return contentType ? contentType.split(':')[1].trim().split(';')[0] : ''; } // 콘텐츠 유형 허용 여부 검사 function isContentTypeAllowed(contentType) { if (settings.contentTypes.include.length > 0 && !settings.contentTypes.include.includes(contentType)) { return false; } if (settings.contentTypes.exclude.length > 0 && settings.contentTypes.exclude.includes(contentType)) { return false; } return true; } // 콘텐츠 품질 평가 함수 function evaluateContentQuality(text) { const wordCount = text.split(/\s+/).length; return wordCount; } // 키워드 분류 함수 function classifyKeywords(text) { const keywords = { '교육': ['학교', '교육', '학생', '교수', '강의'], '기술': ['기술', '소프트웨어', '하드웨어', '프로그래밍', '개발'], '뉴스': ['뉴스', '속보', '기사', '보도'], '엔터테인먼트': ['영화', '음악', '연예', '게임', '드라마'], '스포츠': ['축구', '야구', '농구', '경기', '토너먼트'] // 추가 키워드 및 카테고리 }; for (const [category, kws] of Object.entries(keywords)) { if (kws.some(kw => text.includes(kw))) { return category; } } return '기타'; } // CSV 다운로드 함수 function downloadCSV() { if (data.length === 0) { log('다운로드할 데이터가 없습니다.', 'warning'); return; } const csvRows = [ ["사이트 이름", "주소", "설명", "분류", "품질점수"] ]; data.forEach(d => { csvRows.push([ `"${escapeCSV(d.name)}"`, `"${escapeCSV(d.url)}"`, `"${escapeCSV(d.description)}"`, `"${escapeCSV(d.category)}"`, `"${d.quality}"` ].join(",")); }); const csvContent = "data:text/csv;charset=utf-8," + csvRows.join("\n"); const encodedUri = encodeURI(csvContent); const link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "data.csv"); document.body.appendChild(link); link.click(); document.body.removeChild(link); log('CSV 파일이 다운로드되었습니다.', 'success'); } // JSON 다운로드 함수 function downloadJSON() { if (data.length === 0) { log('다운로드할 데이터가 없습니다.', 'warning'); return; } const jsonContent = JSON.stringify(data, null, 2); const blob = new Blob([jsonContent], { type: "application/json" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", "data.json"); document.body.appendChild(link); link.click(); document.body.removeChild(link); log('JSON 파일이 다운로드되었습니다.', 'success'); } // CSV 이스케이프 함수 function escapeCSV(str) { if (!str) return ''; return str.replace(/"/g, '""'); } // 테이블 필터링 함수 function filterTable(keyword) { $('#data-table-body tr').each(function() { const rowText = $(this).text().toLowerCase(); if (rowText.includes(keyword.toLowerCase())) { $(this).show(); } else { $(this).hide(); } }); } // URL 유효성 검사 함수 function isValidURL(url) { try { new URL(url); return true; } catch (_) { return false; } } // 다음 페이지 수 결정 함수 function determineTotalPages() { // 각 검색 엔진에서 총 페이지 수를 결정하는 로직을 추가할 수 있습니다. // 현재는 설정된 maxPages 사용 return settings.maxPages; } // 딜레이 함수 function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // 초기화 함수 function init() { createUI(); if (isCrawling) { log('크롤링이 이전에 중단된 상태에서 다시 시작됩니다.', 'info'); setButtonStates(); crawlPage(currentDepth); // 페이지 로드 후 크롤링 재개 } else { log('크롤러가 초기화되었습니다.', 'info'); } } // 페이지 로드 시 초기화 window.addEventListener('load', init); // 모달 링크 추출 함수 (심층 크롤링 보조) function extractLinks(pageDoc) { const links = []; const anchorTags = pageDoc.querySelectorAll('a[href]'); anchorTags.forEach(a => { let href = a.getAttribute('href'); if (href.startsWith('/url?q=')) { href = new URLSearchParams(href.substring(7)).get('q'); } if (isValidURL(href)) { links.push(href); } }); return links; } // 페이지 언어 감지 함수 async function getPageLanguage(url) { try { const response = await GM_xmlhttpRequestPromise(url); const pageHtml = response.responseText; const parser = new DOMParser(); const pageDoc = parser.parseFromString(pageHtml, 'text/html'); const lang = pageDoc.documentElement.lang || ''; return lang.split('-')[0]; // 예: 'en-US' -> 'en' } catch (error) { log(`언어 감지 실패: ${url} - ${error.message}`, 'error'); return ''; } } // 스케줄링 크롤링 함수 function scheduleCrawling() { if (!settings.schedule.enabled) return; const [hours, minutes] = settings.schedule.startTime.split(':').map(Number); const now = new Date(); const start = new Date(); start.setHours(hours, minutes, 0, 0); if (start < now) { start.setDate(start.getDate() + 1); // 다음 날로 설정 } const firstDelay = start - now; setTimeout(() => { startCrawling(); setInterval(() => { if (!isCrawling) { startCrawling(); } }, settings.schedule.interval); }, firstDelay); log(`크롤링 스케줄이 설정되었습니다. 시작 시간: ${settings.schedule.startTime}, 간격: ${settings.schedule.interval / 1000}초`, 'info'); }})(); 설정 쪽 다양하면서도 세심하게 만드셈
크롤링하는 사이트를 더 확실하게 할 수 있는 방법들을 추가하셈
- Assistant
Certainly! Enhancing your Advanced Web Crawler script involves both expanding the Settings UI for more comprehensive user control and improving the crawling logic to make site selection more reliable and precise. Below, I’ve incorporated these enhancements into your script:
-
Enhanced Settings UI:
- Per Search Engine Settings: Allow users to customize settings for each search engine individually.
- Advanced Filtering Options: Add options for advanced filters like date ranges, specific regions, and more.
- Improved Layout & Usability: Organize settings into collapsible sections for better readability and ease of use.
- Reset Settings: Provide an option to reset settings to default values.
-
Improved Crawling Logic:
- Robust Search Result Extraction: Utilize more reliable selectors and fallback mechanisms to adapt to changes in search engine layouts.
- Dynamic Search Engine Support: Allow easy addition of new search engines with customizable extraction logic.
- Error Handling Enhancements: Improve handling of unexpected errors like captchas or rate limiting.
Below is the updated script incorporating these enhancements:
javascript// ==UserScript== // @name Advanced Web Crawler Enhanced // @namespace http://tampermonkey.net/ // @version 2.1 // @description 고급 웹 크롤러 스크립트 with Enhanced Settings and Features // @author Your Name // @match https://www.google.com/search* // @match https://www.bing.com/search* // @match https://search.yahoo.com/search* // @match https://duckduckgo.com/* // @match https://www.baidu.com/s* // @match https://www.yandex.com/search/* // @match https://search.naver.com/search* // @match https://search.daum.net/search* // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @connect * // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js // ==/UserScript== (function() { 'use strict'; // 기본 설정 const defaultSettings = { delay: 3000, maxPages: 5, userAgent: 'AdvancedWebCrawler/2.1', blacklist: [], whitelist: [], contentTypes: { include: ['text/html'], exclude: [] }, timeout: 10000, includeKeywords: [], excludeKeywords: [], language: [], minWordCount: 100, maxWordCount: 10000, maxDepth: 2, proxy: '', regexInclude: [], regexExclude: [], dataFields: { name: true, url: true, description: true, html: false, category: true, quality: true }, schedule: { enabled: false, startTime: '00:00', interval: 3600000 }, searchEngines: { google: { enabled: true, specificSettings: { // Example: Add Google-specific settings here } }, bing: { enabled: true, specificSettings: {} }, yahoo: { enabled: true, specificSettings: {} }, duckduckgo: { enabled: true, specificSettings: {} }, baidu: { enabled: true, specificSettings: {} }, yandex: { enabled: true, specificSettings: {} }, naver: { enabled: true, specificSettings: {} }, daum: { enabled: true, specificSettings: {} } }, advancedFilters: { dateRange: '', // e.g., 'past24h', 'pastweek', 'pastmonth' region: '', // e.g., 'US', 'KR' safeSearch: true } }; // Load settings with defaults const settings = { delay: parseInt(GM_getValue('delay', defaultSettings.delay), 10), maxPages: parseInt(GM_getValue('maxPages', defaultSettings.maxPages), 10), userAgent: GM_getValue('userAgent', defaultSettings.userAgent), blacklist: GM_getValue('blacklist', defaultSettings.blacklist), whitelist: GM_getValue('whitelist', defaultSettings.whitelist), contentTypes: GM_getValue('contentTypes', defaultSettings.contentTypes), timeout: parseInt(GM_getValue('timeout', defaultSettings.timeout), 10), includeKeywords: GM_getValue('includeKeywords', defaultSettings.includeKeywords), excludeKeywords: GM_getValue('excludeKeywords', defaultSettings.excludeKeywords), language: GM_getValue('language', defaultSettings.language), minWordCount: parseInt(GM_getValue('minWordCount', defaultSettings.minWordCount), 10), maxWordCount: parseInt(GM_getValue('maxWordCount', defaultSettings.maxWordCount), 10), maxDepth: parseInt(GM_getValue('maxDepth', defaultSettings.maxDepth), 10), proxy: GM_getValue('proxy', defaultSettings.proxy), regexInclude: GM_getValue('regexInclude', defaultSettings.regexInclude), regexExclude: GM_getValue('regexExclude', defaultSettings.regexExclude), dataFields: GM_getValue('dataFields', defaultSettings.dataFields), schedule: GM_getValue('schedule', defaultSettings.schedule), searchEngines: GM_getValue('searchEngines', defaultSettings.searchEngines), advancedFilters: GM_getValue('advancedFilters', defaultSettings.advancedFilters) }; // Initialize crawling state let visitedUrls = GM_getValue('visitedUrls', []); let logs = GM_getValue('logs', []); let data = GM_getValue('data', []); let isCrawling = GM_getValue('isCrawling', false); let currentPage = GM_getValue('currentPage', 1); let totalPages = GM_getValue('totalPages', settings.maxPages); let progress = GM_getValue('progress', 0); let currentDepth = GM_getValue('currentDepth', 0); // UI Creation function createUI() { const style = ` /* Enhanced Styles */ #crawler-container { position: fixed; top: 10px; right: 10px; width: 800px; height: 900px; background: #fff; border: 1px solid #ccc; z-index: 10000; font-family: Arial, sans-serif; box-shadow: 0 4px 8px rgba(0,0,0,0.2); overflow: hidden; } #crawler-tabs { display: flex; background: #f1f1f1; } .crawler-tab { flex: 1; padding: 10px; text-align: center; cursor: pointer; } .crawler-tab.active { background: #ddd; } #crawler-content { padding: 10px; overflow: auto; height: 780px; } table { width: 100%; border-collapse: collapse; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } th { background-color: #f2f2f2; } tr:hover { background-color: #f5f5f5; } .progress-bar { width: 100%; background-color: #f3f3f3; border: 1px solid #ccc; border-radius: 5px; overflow: hidden; margin-bottom: 10px; } .progress-bar-fill { height: 25px; background-color: #4caf50; width: 0%; transition: width 0.2s; } .modal { display: none; position: fixed; z-index: 10001; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); } .modal-content { background-color: #fff; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 80%; max-height: 80%; overflow-y: auto; } .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; } .control-buttons { margin: 10px 0; } .control-buttons button { padding: 10px 20px; margin-right: 10px; cursor: pointer; } .status-text { margin-top: 10px; font-weight: bold; } /* Settings Section Styles */ .settings-section { margin-bottom: 15px; } .settings-section label { display: block; margin-bottom: 5px; font-weight: bold; } .settings-section input[type="text"], .settings-section input[type="number"], .settings-section textarea, .settings-section select { width: 100%; padding: 5px; box-sizing: border-box; } .settings-section .checkbox-group { display: flex; flex-wrap: wrap; } .settings-section .checkbox-group label { margin-right: 10px; } .collapsible { background-color: #f1f1f1; cursor: pointer; padding: 10px; width: 100%; border: none; text-align: left; outline: none; font-size: 16px; } .active + .content { display: block; } .content { display: none; padding: 0 18px; overflow: hidden; } `; $('head').append(`<style>${style}</style>`); const container = $(` <div id="crawler-container"> <div id="crawler-tabs"> <div class="crawler-tab ${currentTab() === 'logs' ? 'active' : ''}" data-tab="logs" title="로그 보기">📜 로그</div> <div class="crawler-tab ${currentTab() === 'data' ? 'active' : ''}" data-tab="data" title="수집된 데이터 보기">📊 데이터</div> <div class="crawler-tab ${currentTab() === 'settings' ? 'active' : ''}" data-tab="settings" title="설정 변경">⚙️ 설정</div> </div> <div id="crawler-content"> <div id="tab-logs" style="display: ${currentTab() === 'logs' ? 'block' : 'none'};"> <div class="progress-bar"> <div class="progress-bar-fill" style="width: ${progress.toFixed(2)}%;"></div> </div> <div class="status-text">진행률: ${progress.toFixed(2)}% (${currentPage}/${totalPages} 페이지)</div> <div class="control-buttons"> <button id="start-crawling" title="크롤링을 시작합니다." ${isCrawling ? 'disabled' : ''}>▶ 시작</button> <button id="stop-crawling" title="크롤링을 중지합니다." ${isCrawling ? '' : 'disabled'}>■ 중지</button> <button id="download-csv" title="수집된 데이터를 CSV 파일로 다운로드합니다.">📥 CSV 다운로드</button> <button id="download-json" title="수집된 데이터를 JSON 파일로 다운로드합니다.">📥 JSON 다운로드</button> </div> <div id="log-messages" style="height: 400px; overflow-y: auto;">로그 내용이 여기에 표시됩니다.</div> </div> <div id="tab-data" style="display: ${currentTab() === 'data' ? 'block' : 'none'};"> <input type="text" id="search-filter" placeholder="검색 필터..." title="데이터 필터링을 위한 키워드를 입력하세요." style="width: 100%; padding: 5px; margin-bottom: 10px;"> <table> <thead> <tr> <th>사이트 이름</th> <th>주소</th> <th>설명</th> <th>HTML</th> <th>분류</th> <th>품질</th> </tr> </thead> <tbody id="data-table-body"> <!-- 데이터 행이 여기에 추가됩니다. --> </tbody> </table> </div> <div id="tab-settings" style="display: ${currentTab() === 'settings' ? 'block' : 'none'};"> <h3>설정</h3> <!-- Enhanced Settings Sections --> <button type="button" class="collapsible">크롤링 설정</button> <div class="content"> <!-- 크롤링 설정 섹션 --> <div class="settings-section"> <label for="delay-input">크롤링 딜레이 (ms):</label> <input type="number" id="delay-input" value="${settings.delay}" title="크롤링 요청 사이의 딜레이를 밀리초 단위로 설정하세요." min="500" step="500"> </div> <div class="settings-section"> <label for="max-pages-input">최대 크롤링 페이지 수:</label> <input type="number" id="max-pages-input" value="${settings.maxPages}" title="크롤링할 최대 페이지 수를 설정하세요." min="1"> </div> <div class="settings-section"> <label for="user-agent-input">사용자 에이전트(User-Agent):</label> <input type="text" id="user-agent-input" value="${settings.userAgent}" title="크롤링에 사용할 사용자 에이전트를 입력하세요."> </div> <!-- 콘텐츠 유형 섹션 --> <div class="settings-section"> <label>콘텐츠 유형:</label> <div> <strong>포함할 유형:</strong> <textarea id="content-include-input" rows="3" title="크롤링할 콘텐츠 유형을 입력하세요. 각 유형은 쉼표로 구분됩니다. 예: text/html, application/json">${settings.contentTypes.include.join(', ')}</textarea> </div> <div> <strong>제외할 유형:</strong> <textarea id="content-exclude-input" rows="3" title="크롤링에서 제외할 콘텐츠 유형을 입력하세요. 각 유형은 쉼표로 구분됩니다. 예: image/jpeg, video/mp4">${settings.contentTypes.exclude.join(', ')}</textarea> </div> </div> <!-- 타임아웃 섹션 --> <div class="settings-section"> <label for="timeout-input">크롤링 타임아웃 (ms):</label> <input type="number" id="timeout-input" value="${settings.timeout}" title="크롤링 요청의 타임아웃을 밀리초 단위로 설정하세요." min="1000" step="1000"> </div> <!-- 키워드 섹션 --> <div class="settings-section"> <label for="include-keywords-input">포함할 키워드:</label> <textarea id="include-keywords-input" rows="3" style="width: 100%;" title="크롤링할 페이지에 반드시 포함되어야 하는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.">${settings.includeKeywords.join('\n')}</textarea> </div> <div class="settings-section"> <label for="exclude-keywords-input">제외할 키워드:</label> <textarea id="exclude-keywords-input" rows="3" style="width: 100%;" title="크롤링할 페이지에 포함되면 안 되는 키워드를 입력하세요. 각 키워드는 줄바꿈으로 구분됩니다.">${settings.excludeKeywords.join('\n')}</textarea> </div> <!-- 정규 표현식 키워드 섹션 --> <div class="settings-section"> <label for="regex-include-input">포함할 키워드 (정규 표현식):</label> <textarea id="regex-include-input" rows="3" style="width: 100%;" title="포함할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.">${settings.regexInclude.join('\n')}</textarea> </div> <div class="settings-section"> <label for="regex-exclude-input">제외할 키워드 (정규 표현식):</label> <textarea id="regex-exclude-input" rows="3" style="width: 100%;" title="제외할 키워드의 정규 표현식을 입력하세요. 각 패턴은 줄바꿈으로 구분됩니다.">${settings.regexExclude.join('\n')}</textarea> </div> <!-- 언어 필터링 섹션 --> <div class="settings-section"> <label for="language-select">언어 필터링:</label> <select id="language-select" multiple size="5" title="크롤링할 언어를 선택하세요. 선택하지 않으면 모든 언어가 포함됩니다."> <option value="en" ${settings.language.includes('en') ? 'selected' : ''}>영어 (en)</option> <option value="ko" ${settings.language.includes('ko') ? 'selected' : ''}>한국어 (ko)</option> <option value="zh" ${settings.language.includes('zh') ? 'selected' : ''}>중국어 (zh)</option> <option value="ja" ${settings.language.includes('ja') ? 'selected' : ''}>일본어 (ja)</option> <option value="ru" ${settings.language.includes('ru') ? 'selected' : ''}>러시아어 (ru)</option> <!-- 추가 언어 옵션 --> </select> </div> <!-- 단어 수 섹션 --> <div class="settings-section"> <label for="min-word-count-input">최소 단어 수:</label> <input type="number" id="min-word-count-input" value="${settings.minWordCount}" title="수집할 페이지의 최소 단어 수를 설정하세요." min="10" step="10"> </div> <div class="settings-section"> <label for="max-word-count-input">최대 단어 수:</label> <input type="number" id="max-word-count-input" value="${settings.maxWordCount}" title="수집할 페이지의 최대 단어 수를 설정하세요." min="100" step="100"> </div> <!-- 심층 크롤링 섹션 --> <div class="settings-section"> <label for="max-depth-input">최대 크롤링 깊이:</label> <input type="number" id="max-depth-input" value="${settings.maxDepth}" title="링크를 추적할 최대 깊이를 설정하세요." min="1" step="1"> </div> <!-- 프록시 섹션 --> <div class="settings-section"> <label for="proxy-input">프록시 서버:</label> <input type="text" id="proxy-input" value="${settings.proxy}" placeholder="http://proxyserver:port" title="프록시 서버 주소를 입력하세요. (옵션)"> </div> <!-- 데이터 필드 섹션 --> <div class="settings-section"> <label>수집할 데이터 필드:</label> <div class="checkbox-group"> <label><input type="checkbox" id="field-name" ${settings.dataFields.name ? 'checked' : ''}> 사이트 이름</label> <label><input type="checkbox" id="field-url" ${settings.dataFields.url ? 'checked' : ''}> 주소</label> <label><input type="checkbox" id="field-description" ${settings.dataFields.description ? 'checked' : ''}> 설명</label> <label><input type="checkbox" id="field-html" ${settings.dataFields.html ? 'checked' : ''}> HTML</label> <label><input type="checkbox" id="field-category" ${settings.dataFields.category ? 'checked' : ''}> 분류</label> <label><input type="checkbox" id="field-quality" ${settings.dataFields.quality ? 'checked' : ''}> 품질점수</label> </div> </div> <button id="save-settings" title="설정을 저장합니다." style="margin-top: 10px; padding: 5px 10px;">저장</button> <button id="reset-settings" title="설정을 기본값으로 재설정합니다." style="margin-top: 10px; padding: 5px 10px;">기본값으로 재설정</button> </div> <button type="button" class="collapsible">고급 필터링</button> <div class="content"> <div class="settings-section"> <label for="date-range-select">날짜 범위:</label> <select id="date-range-select" title="크롤링할 날짜 범위를 선택하세요."> <option value="" ${!settings.advancedFilters.dateRange ? 'selected' : ''}>모든 시간</option> <option value="past24h" ${settings.advancedFilters.dateRange === 'past24h' ? 'selected' : ''}>지난 24시간</option> <option value="pastweek" ${settings.advancedFilters.dateRange === 'pastweek' ? 'selected' : ''}>지난 주</option> <option value="pastmonth" ${settings.advancedFilters.dateRange === 'pastmonth' ? 'selected' : ''}>지난 달</option> <!-- 추가 날짜 옵션 --> </select> </div> <div class="settings-section"> <label for="region-select">지역:</label> <select id="region-select" title="크롤링할 지역을 선택하세요."> <option value="" ${!settings.advancedFilters.region ? 'selected' : ''}>모든 지역</option> <option value="US" ${settings.advancedFilters.region === 'US' ? 'selected' : ''}>미국 (US)</option> <option value="KR" ${settings.advancedFilters.region === 'KR' ? 'selected' : ''}>한국 (KR)</option> <option value="JP" ${settings.advancedFilters.region === 'JP' ? 'selected' : ''}>일본 (JP)</option> <option value="CN" ${settings.advancedFilters.region === 'CN' ? 'selected' : ''}>중국 (CN)</option> <!-- 추가 지역 옵션 --> </select> </div> <div class="settings-section"> <label for="safe-search-checkbox">안전 검색:</label> <input type="checkbox" id="safe-search-checkbox" ${settings.advancedFilters.safeSearch ? 'checked' : ''} title="안전 검색을 활성화하세요."> </div> </div> <button type="button" class="collapsible">검색 엔진별 설정</button> <div class="content"> ${Object.keys(settings.searchEngines).map(engine => ` <div class="settings-section"> <label><input type="checkbox" id="engine-${engine}" ${settings.searchEngines[engine].enabled ? 'checked' : ''}> ${capitalize(engine)}</label> <!-- Placeholder for engine-specific settings --> <div class="engine-specific-settings" id="specific-settings-${engine}" style="display: none; margin-left: 20px; margin-top: 10px;"> <!-- Add engine-specific settings here --> <p>추가 설정은 추후에 구현할 수 있습니다.</p> </div> </div> `).join('')} </div> <button type="button" class="collapsible">블랙리스트/화이트리스트</button> <div class="content"> <!-- 블랙리스트 섹션 --> <div class="settings-section"> <label for="blacklist-input">블랙리스트 도메인:</label> <textarea id="blacklist-input" rows="5" style="width: 100%;" title="크롤링에서 제외할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.">${settings.blacklist.join('\n')}</textarea> </div> <!-- 화이트리스트 섹션 --> <div class="settings-section"> <label for="whitelist-input">화이트리스트 도메인:</label> <textarea id="whitelist-input" rows="5" style="width: 100%;" title="크롤링을 허용할 도메인을 입력하세요. 각 도메인은 줄바꿈으로 구분됩니다.">${settings.whitelist.join('\n')}</textarea> </div> </div> <button type="button" class="collapsible">스케줄링</button> <div class="content"> <div class="settings-section"> <label>크롤링 스케줄링:</label> <div class="checkbox-group"> <label><input type="checkbox" id="schedule-enabled" ${settings.schedule.enabled ? 'checked' : ''} title="크롤링 작업을 예약하려면 체크하세요."> 스케줄링 활성화</label> </div> <div id="schedule-options" style="display: ${settings.schedule.enabled ? 'block' : 'none'}; margin-top: 10px;"> <label for="start-time-input">시작 시간 (HH:MM):</label> <input type="time" id="start-time-input" value="${settings.schedule.startTime}" title="크롤링을 시작할 시간을 설정하세요."> <label for="interval-input">크롤링 간격 (밀리초):</label> <input type="number" id="interval-input" value="${settings.schedule.interval}" title="크롤링 작업 간의 간격을 밀리초 단위로 설정하세요." min="60000" step="60000"> </div> </div> </div> <button type="button" class="collapsible">고급 필터링</button> <div class="content"> <!-- Advanced Filtering Section (already handled above) --> </div> <!-- Save and Reset Buttons --> <div class="control-buttons"> <button id="save-settings" title="설정을 저장합니다." style="padding: 5px 10px;">저장</button> <button id="reset-settings" title="설정을 기본값으로 재설정합니다." style="padding: 5px 10px;">기본값으로 재설정</button> </div> </div> </div> <!-- Modal for Viewing HTML Content --> <div id="html-modal" class="modal"> <div class="modal-content"> <span class="close">×</span> <pre id="modal-html-content" style="white-space: pre-wrap;"></pre> </div> </div> </div> `); $('body').append(container); // Initialize Collapsible Sections $('.collapsible').each(function() { $(this).on('click', function() { this.classList.toggle('active'); const content = $(this).next('.content'); if (content.css('display') === 'block') { content.slideUp(); } else { content.slideDown(); } }); }); // Tab Switching $('.crawler-tab').on('click', function() { const tab = $(this).data('tab'); $('.crawler-tab').removeClass('active'); $(this).addClass('active'); $('#crawler-content > div').hide(); $(`#tab-${tab}`).show(); saveCurrentTab(tab); }); // Keyboard Shortcuts $(document).on('keydown', function(e) { if (e.ctrlKey) { switch (e.key) { case '1': $('.crawler-tab[data-tab="logs"]').click(); break; case '2': $('.crawler-tab[data-tab="data"]').click(); break; case '3': $('.crawler-tab[data-tab="settings"]').click(); break; case 's': e.preventDefault(); saveSettings(); break; case 'p': e.preventDefault(); if (!isCrawling) startCrawling(); break; case 'q': e.preventDefault(); if (isCrawling) stopCrawling(); break; case 'd': e.preventDefault(); downloadCSV(); break; case 'j': e.preventDefault(); downloadJSON(); break; } } }); // Save Settings Button Event $('#save-settings').on('click', saveSettings); // Reset Settings Button Event $('#reset-settings').on('click', resetSettings); // Download Buttons $('#download-csv').on('click', downloadCSV); $('#download-json').on('click', downloadJSON); // Search Filter $('#search-filter').on('input', function() { filterTable($(this).val()); }); // Schedule Options Toggle $('#schedule-enabled').on('change', function() { if ($(this).is(':checked')) { $('#schedule-options').slideDown(); } else { $('#schedule-options').slideUp(); } }); // Modal Functionality const modal = document.getElementById("html-modal"); const span = document.getElementsByClassName("close")[0]; span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } // Start and Stop Crawling Buttons $('#start-crawling').on('click', startCrawling); $('#stop-crawling').on('click', stopCrawling); // Engine-specific Settings Toggle Object.keys(settings.searchEngines).forEach(engine => { $(`#engine-${engine}`).on('change', function() { if ($(this).is(':checked')) { $(`#specific-settings-${engine}`).slideDown(); } else { $(`#specific-settings-${engine}`).slideUp(); } }); // Initialize display based on current settings if (settings.searchEngines[engine].enabled) { $(`#specific-settings-${engine}`).show(); } else { $(`#specific-settings-${engine}`).hide(); } }); // Initial UI Updates updateLogsUI(); updateDataUI(); } function currentTab() { return GM_getValue('currentTab', 'logs'); } function saveCurrentTab(tab) { GM_setValue('currentTab', tab); } // Logging Function function log(message, type = 'info') { const timestamp = new Date().toLocaleString(); logs.push({ timestamp, message, type }); GM_setValue('logs', logs); updateLogsUI(); // Map type to console methods switch(type) { case 'info': console.info(`[${timestamp}] [INFO] ${message}`); break; case 'warning': console.warn(`[${timestamp}] [WARNING] ${message}`); break; case 'error': console.error(`[${timestamp}] [ERROR] ${message}`); break; case 'success': console.log(`%c[${timestamp}] [SUCCESS] ${message}`, 'color: green; font-weight: bold;'); break; default: console.log(`[${timestamp}] [${type.toUpperCase()}] ${message}`); } } function updateLogsUI() { const logHtml = logs.map(log => `<div>[${log.timestamp}] [${log.type.toUpperCase()}] ${log.message}</div>`).join(''); $('#log-messages').html(logHtml); $('.progress-bar-fill').css('width', `${progress.toFixed(2)}%`); $('.status-text').text(`진행률: ${progress.toFixed(2)}% (${currentPage}/${totalPages} 페이지)`); } // Data Update Function function updateDataUI() { const filter = $('#search-filter').val().toLowerCase(); let filteredData = data; if (filter) { filteredData = data.filter(item => (settings.dataFields.name && item.name.toLowerCase().includes(filter)) || (settings.dataFields.url && item.url.toLowerCase().includes(filter)) || (settings.dataFields.description && item.description.toLowerCase().includes(filter)) || (settings.dataFields.category && item.category.toLowerCase().includes(filter)) ); } let tableHtml = filteredData.map(item => ` <tr> ${settings.dataFields.name ? `<td>${escapeHTML(item.name)}</td>` : ''} ${settings.dataFields.url ? `<td><a href="${escapeHTML(item.url)}" target="_blank">${escapeHTML(item.url)}</a></td>` : ''} ${settings.dataFields.description ? `<td>${escapeHTML(item.description)}</td>` : ''} ${settings.dataFields.html ? `<td><button class="view-html" data-html="${encodeURIComponent(item.html)}" title="HTML 내용을 봅니다.">보기</button></td>` : ''} ${settings.dataFields.category ? `<td>${escapeHTML(item.category)}</td>` : ''} ${settings.dataFields.quality ? `<td>${escapeHTML(item.quality.toString())}</td>` : ''} </tr> `).join(''); $('#data-table-body').html(tableHtml); // HTML View Modal $('.view-html').off('click').on('click', function() { const htmlContent = decodeURIComponent($(this).data('html')); $('#modal-html-content').text(htmlContent); $('#html-modal').show(); }); } // HTML Escaping Function function escapeHTML(str) { if (!str) return ''; return str.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // Save Settings Function function saveSettings() { // General Settings const delay = parseInt($('#delay-input').val(), 10); settings.delay = isNaN(delay) ? defaultSettings.delay : delay; const maxPages = parseInt($('#max-pages-input').val(), 10); settings.maxPages = isNaN(maxPages) ? defaultSettings.maxPages : maxPages; const userAgent = $('#user-agent-input').val().trim(); settings.userAgent = userAgent || defaultSettings.userAgent; const contentInclude = $('#content-include-input').val().split(',').map(ct => ct.trim()).filter(ct => ct); const contentExclude = $('#content-exclude-input').val().split(',').map(ct => ct.trim()).filter(ct => ct); settings.contentTypes.include = contentInclude.length > 0 ? contentInclude : defaultSettings.contentTypes.include; settings.contentTypes.exclude = contentExclude.length > 0 ? contentExclude : defaultSettings.contentTypes.exclude; const timeout = parseInt($('#timeout-input').val(), 10); settings.timeout = isNaN(timeout) ? defaultSettings.timeout : timeout; const includeKeywords = $('#include-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw); settings.includeKeywords = includeKeywords; const excludeKeywords = $('#exclude-keywords-input').val().split('\n').map(kw => kw.trim()).filter(kw => kw); settings.excludeKeywords = excludeKeywords; const regexInclude = $('#regex-include-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx); settings.regexInclude = regexInclude; const regexExclude = $('#regex-exclude-input').val().split('\n').map(rx => rx.trim()).filter(rx => rx); settings.regexExclude = regexExclude; const language = $('#language-select').val() || []; settings.language = language; const minWordCount = parseInt($('#min-word-count-input').val(), 10); settings.minWordCount = isNaN(minWordCount) ? defaultSettings.minWordCount : minWordCount; const maxWordCount = parseInt($('#max-word-count-input').val(), 10); settings.maxWordCount = isNaN(maxWordCount) ? defaultSettings.maxWordCount : maxWordCount; const maxDepth = parseInt($('#max-depth-input').val(), 10); settings.maxDepth = isNaN(maxDepth) ? defaultSettings.maxDepth : maxDepth; const proxy = $('#proxy-input').val().trim(); settings.proxy = proxy || defaultSettings.proxy; // Data Fields Settings settings.dataFields.name = $('#field-name').is(':checked'); settings.dataFields.url = $('#field-url').is(':checked'); settings.dataFields.description = $('#field-description').is(':checked'); settings.dataFields.html = $('#field-html').is(':checked'); settings.dataFields.category = $('#field-category').is(':checked'); settings.dataFields.quality = $('#field-quality').is(':checked'); // Advanced Filters const dateRange = $('#date-range-select').val(); settings.advancedFilters.dateRange = dateRange || defaultSettings.advancedFilters.dateRange; const region = $('#region-select').val(); settings.advancedFilters.region = region || defaultSettings.advancedFilters.region; const safeSearch = $('#safe-search-checkbox').is(':checked'); settings.advancedFilters.safeSearch = safeSearch; // Schedule Settings settings.schedule.enabled = $('#schedule-enabled').is(':checked'); const startTime = $('#start-time-input').val(); settings.schedule.startTime = startTime || defaultSettings.schedule.startTime; const interval = parseInt($('#interval-input').val(), 10); settings.schedule.interval = isNaN(interval) ? defaultSettings.schedule.interval : interval; // Search Engines Settings Object.keys(settings.searchEngines).forEach(engine => { const enabled = $(`#engine-${engine}`).is(':checked'); settings.searchEngines[engine].enabled = enabled; // Additional per-engine settings can be saved here }); // Blacklist and Whitelist const blacklist = $('#blacklist-input').val().split('\n').map(d => d.trim()).filter(d => d); settings.blacklist = blacklist; const whitelist = $('#whitelist-input').val().split('\n').map(d => d.trim()).filter(d => d); settings.whitelist = whitelist; // Save to storage GM_setValue('delay', settings.delay); GM_setValue('maxPages', settings.maxPages); GM_setValue('userAgent', settings.userAgent); GM_setValue('contentTypes', settings.contentTypes); GM_setValue('timeout', settings.timeout); GM_setValue('includeKeywords', settings.includeKeywords); GM_setValue('excludeKeywords', settings.excludeKeywords); GM_setValue('regexInclude', settings.regexInclude); GM_setValue('regexExclude', settings.regexExclude); GM_setValue('language', settings.language); GM_setValue('minWordCount', settings.minWordCount); GM_setValue('maxWordCount', settings.maxWordCount); GM_setValue('maxDepth', settings.maxDepth); GM_setValue('proxy', settings.proxy); GM_setValue('dataFields', settings.dataFields); GM_setValue('advancedFilters', settings.advancedFilters); GM_setValue('schedule', settings.schedule); GM_setValue('searchEngines', settings.searchEngines); GM_setValue('blacklist', settings.blacklist); GM_setValue('whitelist', settings.whitelist); // Update totalPages totalPages = settings.maxPages; GM_setValue('totalPages', totalPages); log('설정이 저장되었습니다.', 'success'); // Schedule Crawling if Enabled if (settings.schedule.enabled) { scheduleCrawling(); } } // Reset Settings Function function resetSettings() { if (confirm('모든 설정을 기본값으로 재설정하시겠습니까?')) { GM_setValue('delay', defaultSettings.delay); GM_setValue('maxPages', defaultSettings.maxPages); GM_setValue('userAgent', defaultSettings.userAgent); GM_setValue('contentTypes', defaultSettings.contentTypes); GM_setValue('timeout', defaultSettings.timeout); GM_setValue('includeKeywords', defaultSettings.includeKeywords); GM_setValue('excludeKeywords', defaultSettings.excludeKeywords); GM_setValue('regexInclude', defaultSettings.regexInclude); GM_setValue('regexExclude', defaultSettings.regexExclude); GM_setValue('language', defaultSettings.language); GM_setValue('minWordCount', defaultSettings.minWordCount); GM_setValue('maxWordCount', defaultSettings.maxWordCount); GM_setValue('maxDepth', defaultSettings.maxDepth); GM_setValue('proxy', defaultSettings.proxy); GM_setValue('dataFields', defaultSettings.dataFields); GM_setValue('advancedFilters', defaultSettings.advancedFilters); GM_setValue('schedule', defaultSettings.schedule); GM_setValue('searchEngines', defaultSettings.searchEngines); GM_setValue('blacklist', defaultSettings.blacklist); GM_setValue('whitelist', defaultSettings.whitelist); // Reload settings into variables Object.assign(settings, defaultSettings); visitedUrls = []; logs = []; data = []; isCrawling = false; currentPage = 1; totalPages = settings.maxPages; progress = 0; currentDepth = 0; GM_setValue('visitedUrls', visitedUrls); GM_setValue('logs', logs); GM_setValue('data', data); GM_setValue('isCrawling', isCrawling); GM_setValue('currentPage', currentPage); GM_setValue('totalPages', totalPages); GM_setValue('progress', progress); GM_setValue('currentDepth', currentDepth); // Update UI Components $('#delay-input').val(settings.delay); $('#max-pages-input').val(settings.maxPages); $('#user-agent-input').val(settings.userAgent); $('#content-include-input').val(settings.contentTypes.include.join(', ')); $('#content-exclude-input').val(settings.contentTypes.exclude.join(', ')); $('#timeout-input').val(settings.timeout); $('#include-keywords-input').val(settings.includeKeywords.join('\n')); $('#exclude-keywords-input').val(settings.excludeKeywords.join('\n')); $('#regex-include-input').val(settings.regexInclude.join('\n')); $('#regex-exclude-input').val(settings.regexExclude.join('\n')); $('#language-select').val(settings.language); $('#min-word-count-input').val(settings.minWordCount); $('#max-word-count-input').val(settings.maxWordCount); $('#max-depth-input').val(settings.maxDepth); $('#proxy-input').val(settings.proxy); $('#field-name').prop('checked', settings.dataFields.name); $('#field-url').prop('checked', settings.dataFields.url); $('#field-description').prop('checked', settings.dataFields.description); $('#field-html').prop('checked', settings.dataFields.html); $('#field-category').prop('checked', settings.dataFields.category); $('#field-quality').prop('checked', settings.dataFields.quality); $('#date-range-select').val(settings.advancedFilters.dateRange); $('#region-select').val(settings.advancedFilters.region); $('#safe-search-checkbox').prop('checked', settings.advancedFilters.safeSearch); // Search Engines Object.keys(settings.searchEngines).forEach(engine => { $(`#engine-${engine}`).prop('checked', settings.searchEngines[engine].enabled); if (settings.searchEngines[engine].enabled) { $(`#specific-settings-${engine}`).show(); } else { $(`#specific-settings-${engine}`).hide(); } }); $('#blacklist-input').val(settings.blacklist.join('\n')); $('#whitelist-input').val(settings.whitelist.join('\n')); // Schedule Settings $('#schedule-enabled').prop('checked', settings.schedule.enabled); $('#start-time-input').val(settings.schedule.startTime); $('#interval-input').val(settings.schedule.interval); log('설정이 기본값으로 재설정되었습니다.', 'success'); updateLogsUI(); updateDataUI(); } // Crawling Functions // Start Crawling Function async function startCrawling() { if (isCrawling) { log('이미 크롤링이 진행 중입니다.', 'warning'); return; } if (!isAnySearchEngineEnabled()) { log('사용할 검색 엔진이 하나도 선택되지 않았습니다.', 'error'); return; } isCrawling = true; GM_setValue('isCrawling', isCrawling); log('크롤링을 시작합니다.', 'info'); setButtonStates(); currentPage = GM_getValue('currentPage', 1); totalPages = GM_getValue('totalPages', settings.maxPages); GM_setValue('totalPages', totalPages); currentDepth = GM_getValue('currentDepth', 0); await crawlPage(currentDepth); } // Stop Crawling Function function stopCrawling() { if (!isCrawling) { log('크롤링이 진행 중이지 않습니다.', 'warning'); return; } isCrawling = false; GM_setValue('isCrawling', isCrawling); log('크롤링이 중지되었습니다.', 'warning'); setButtonStates(); } // Set Button States Function function setButtonStates() { if (isCrawling) { $('#start-crawling').prop('disabled', true); $('#stop-crawling').prop('disabled', false); } else { $('#start-crawling').prop('disabled', false); $('#stop-crawling').prop('disabled', true); } } // Crawling Function async function crawlPage(currentDepth) { try { while (isCrawling && currentPage <= totalPages && currentDepth <= settings.maxDepth) { log(`페이지 ${currentPage} 크롤링 시작. (깊이: ${currentDepth})`, 'info'); const searchResults = extractSearchResults(); if (!searchResults) { log('검색 결과를 찾을 수 없습니다.', 'error'); break; } for (let result of searchResults) { if (!isCrawling) break; const name = result.name; const link = result.url; const description = result.description; // 중복 검사 if (visitedUrls.includes(link)) { log(`중복된 URL 발견: ${link}`, 'warning'); continue; } // 블랙리스트/화이트리스트 검사 if (settings.whitelist.length > 0 && !settings.whitelist.some(domain => link.includes(domain))) { log(`화이트리스트에 없는 도메인: ${link}`, 'warning'); continue; } if (settings.blacklist.some(domain => link.includes(domain))) { log(`블랙리스트에 있는 도메인: ${link}`, 'warning'); continue; } // 언어 필터링 검사 if (settings.language.length > 0) { const pageLanguage = await getPageLanguage(link); if (!settings.language.includes(pageLanguage)) { log(`선택된 언어에 맞지 않는 페이지: ${link} (${pageLanguage})`, 'warning'); continue; } } // 키워드 포함/제외 검사 if (settings.includeKeywords.length > 0 && !settings.includeKeywords.some(kw => link.includes(kw) || description.includes(kw))) { log(`포함 키워드가 없는 URL: ${link}`, 'warning'); continue; } if (settings.excludeKeywords.some(kw => link.includes(kw) || description.includes(kw))) { log(`제외 키워드가 포함된 URL: ${link}`, 'warning'); continue; } // 정규 표현식 필터링 if (settings.regexInclude.length > 0) { const matchesInclude = settings.regexInclude.some(pattern => new RegExp(pattern).test(link) || new RegExp(pattern).test(description)); if (!matchesInclude) { log(`정규 표현식 포함 조건에 맞지 않는 URL: ${link}`, 'warning'); continue; } } if (settings.regexExclude.length > 0) { const matchesExclude = settings.regexExclude.some(pattern => new RegExp(pattern).test(link) || new RegExp(pattern).test(description)); if (matchesExclude) { log(`정규 표현식 제외 조건에 맞는 URL: ${link}`, 'warning'); continue; } } // 데이터 수집 try { const response = await GM_xmlhttpRequestPromise(link); const contentType = getContentType(response); if (!isContentTypeAllowed(contentType)) { log(`허용되지 않은 콘텐츠 유형(${contentType})의 URL: ${link}`, 'warning'); continue; } const pageHtml = response.responseText; const parser = new DOMParser(); const pageDoc = parser.parseFromString(pageHtml, 'text/html'); const textContent = pageDoc.body ? pageDoc.body.innerText : ''; // 단어 수 검사 const wordCount = textContent.split(/\s+/).length; if (wordCount < settings.minWordCount) { log(`단어 수가 최소 기준 (${settings.minWordCount})에 미치지 못하는 URL: ${link} (${wordCount} 단어)`, 'warning'); continue; } if (wordCount > settings.maxWordCount) { log(`단어 수가 최대 기준 (${settings.maxWordCount})을 초과하는 URL: ${link} (${wordCount} 단어)`, 'warning'); continue; } // 콘텐츠 품질 평가 const qualityScore = evaluateContentQuality(textContent); // 키워드 분류 const category = classifyKeywords(textContent); // 조건에 맞는 경우에만 데이터 추가 if (category !== '기타' || qualityScore > 100) { // 예시 조건 const dataEntry = {}; if (settings.dataFields.name) dataEntry.name = name; if (settings.dataFields.url) dataEntry.url = link; if (settings.dataFields.description) dataEntry.description = description; if (settings.dataFields.html) dataEntry.html = pageHtml; if (settings.dataFields.category) dataEntry.category = category; if (settings.dataFields.quality) dataEntry.quality = qualityScore; data.push(dataEntry); GM_setValue('data', data); updateDataUI(); log(`데이터 수집 완료: ${link}`, 'success'); } else { log(`조건에 맞지 않아 데이터에 추가되지 않은 URL: ${link}`, 'info'); } // 링크 추적을 위한 추가 로직 (심층 크롤링) if (currentDepth < settings.maxDepth) { const additionalLinks = extractLinks(pageDoc); for (let additionalLink of additionalLinks) { if (!visitedUrls.includes(additionalLink) && isValidURL(additionalLink)) { visitedUrls.push(additionalLink); } } } } catch (error) { log(`데이터 수집 실패: ${link} - ${error.message}`, 'error'); } visitedUrls.push(link); GM_setValue('visitedUrls', visitedUrls); } // 진행률 업데이트 progress = (currentPage / totalPages) * 100; GM_setValue('progress', progress); updateLogsUI(); // 다음 페이지로 이동 if (currentPage < totalPages && isCrawling) { const nextPageUrl = getNextPageUrl(); if (nextPageUrl) { currentPage++; GM_setValue('currentPage', currentPage); currentDepth++; GM_setValue('currentDepth', currentDepth); log(`다음 페이지로 이동: ${currentPage}`, 'info'); await delay(settings.delay); window.location.href = nextPageUrl; return; } else { log('다음 페이지 링크를 찾을 수 없습니다.', 'error'); break; } } else { break; } } if (isCrawling && currentPage > totalPages) { log('크롤링이 완료되었습니다.', 'success'); isCrawling = false; GM_setValue('isCrawling', isCrawling); setButtonStates(); GM_setValue('progress', 100); $('.progress-bar-fill').css('width', `100%`); $('.status-text').text(`진행률: 100% (${currentPage}/${totalPages} 페이지)`); } } catch (error) { log(`크롤링 중 오류 발생: ${error.message}`, 'error'); } finally { if (!isCrawling) { GM_setValue('isCrawling', isCrawling); setButtonStates(); log('크롤링이 중지되었습니다.', 'info'); } } } // Check if any Search Engine is Enabled function isAnySearchEngineEnabled() { return Object.values(settings.searchEngines).some(engine => engine.enabled); } // Extract Search Results Function function extractSearchResults() { let results = []; const hostname = window.location.hostname; // Google Search Results Extraction if (hostname.includes('google.com') && settings.searchEngines.google.enabled) { const items = document.querySelectorAll('div.g, div[data-hveid]'); items.forEach(item => { const nameElement = item.querySelector('h3'); const linkElement = item.querySelector('a'); let descElement = item.querySelector('.aCOpRe') || item.querySelector('.VwiC3b'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Bing Search Results Extraction else if (hostname.includes('bing.com') && settings.searchEngines.bing.enabled) { const items = document.querySelectorAll('.b_algo'); items.forEach(item => { const nameElement = item.querySelector('h2'); const linkElement = nameElement ? nameElement.querySelector('a') : null; const descElement = item.querySelector('.b_caption p'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Yahoo Search Results Extraction else if (hostname.includes('search.yahoo.com') && settings.searchEngines.yahoo.enabled) { const items = document.querySelectorAll('div.dd.algo'); items.forEach(item => { const nameElement = item.querySelector('h3.title'); const linkElement = nameElement ? nameElement.querySelector('a') : null; const descElement = item.querySelector('.compText p'); const name = nameElement ? nameElement.innerText.trim() : 'No Title'; const link = linkElement ? linkElement.href : ''; const description = descElement ? descElement.innerText.trim() : 'No Description'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Naver Search Results Extraction else if (hostname.includes('naver.com') && settings.searchEngines.naver.enabled) { const items = document.querySelectorAll('.news.mynews.section._prs_nws'); items.forEach(item => { const nameElement = item.querySelector('.news_area .news_tit'); const link = nameElement ? nameElement.href : ''; const description = item.querySelector('.dsc_wrap') ? item.querySelector('.dsc_wrap').innerText.trim() : 'No Description'; const name = nameElement ? nameElement.innerText.trim() : 'No Title'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Daum Search Results Extraction else if (hostname.includes('daum.net') && settings.searchEngines.daum.enabled) { const items = document.querySelectorAll('.wrap_cont div'); items.forEach(item => { const nameElement = item.querySelector('a.f_link_b'); const link = nameElement ? nameElement.href : ''; const description = item.querySelector('.desc') ? item.querySelector('.desc').innerText.trim() : 'No Description'; const name = nameElement ? nameElement.innerText.trim() : 'No Title'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // DuckDuckGo Search Results Extraction else if (hostname.includes('duckduckgo.com') && settings.searchEngines.duckduckgo.enabled) { const items = document.querySelectorAll('.result'); items.forEach(item => { const nameElement = item.querySelector('h2 a.result__a'); const link = nameElement ? nameElement.href : ''; const description = item.querySelector('.result__snippet') ? item.querySelector('.result__snippet').innerText.trim() : 'No Description'; const name = nameElement ? nameElement.innerText.trim() : 'No Title'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Baidu Search Results Extraction else if (hostname.includes('baidu.com') && settings.searchEngines.baidu.enabled) { const items = document.querySelectorAll('.result'); items.forEach(item => { const nameElement = item.querySelector('h3 a'); const link = nameElement ? nameElement.href : ''; const description = item.querySelector('.c-abstract') ? item.querySelector('.c-abstract').innerText.trim() : 'No Description'; const name = nameElement ? nameElement.innerText.trim() : 'No Title'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Yandex Search Results Extraction else if (hostname.includes('yandex.com') && settings.searchEngines.yandex.enabled) { const items = document.querySelectorAll('.serp-item'); items.forEach(item => { const nameElement = item.querySelector('.organic__title-link'); const link = nameElement ? nameElement.href : ''; const description = item.querySelector('.text-container') ? item.querySelector('.text-container').innerText.trim() : 'No Description'; const name = nameElement ? nameElement.innerText.trim() : 'No Title'; if (link && isValidURL(link)) results.push({ name, url: link, description }); }); } // Additional Search Engines can be added here else { log('지원되지 않거나 비활성화된 검색 엔진입니다.', 'warning'); } return results.length > 0 ? results : null; } // Get Next Page URL Function function getNextPageUrl() { let nextPageUrl = null; const hostname = window.location.hostname; if (hostname.includes('google.com') && settings.searchEngines.google.enabled) { const nextLink = document.querySelector('a#pnnext'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('bing.com') && settings.searchEngines.bing.enabled) { const nextLink = document.querySelector('a.sb_pagN'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('search.yahoo.com') && settings.searchEngines.yahoo.enabled) { const nextLink = document.querySelector('a.next'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('naver.com') && settings.searchEngines.naver.enabled) { const nextLink = document.querySelector('.sc_page_inner a.btn_next'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('daum.net') && settings.searchEngines.daum.enabled) { const nextLink = document.querySelector('.paging a.btn_next'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('duckduckgo.com') && settings.searchEngines.duckduckgo.enabled) { const nextLink = document.querySelector('a.js-next-page'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('baidu.com') && settings.searchEngines.baidu.enabled) { const nextLink = document.querySelector('.n'); if (nextLink) nextPageUrl = nextLink.href; } else if (hostname.includes('yandex.com') && settings.searchEngines.yandex.enabled) { const nextLink = document.querySelector('.pager__item_kind_next a'); if (nextLink) nextPageUrl = nextLink.href; } // Additional search engine next page logic can be added here log(`다음 페이지 URL: ${nextPageUrl || '없음'}`, 'info'); return nextPageUrl; } // GM_xmlhttpRequest Wrapped with Promise function GM_xmlhttpRequestPromise(url) { return new Promise((resolve, reject) => { let requestUrl = url; if (settings.proxy) { requestUrl = `${settings.proxy}?url=${encodeURIComponent(url)}`; } GM_xmlhttpRequest({ method: "GET", url: requestUrl, headers: { 'User-Agent': settings.userAgent }, timeout: settings.timeout, onload: function(response) { if (response.status >= 200 && response.status < 300) { resolve(response); } else { reject(new Error(`HTTP Status ${response.status}`)); } }, onerror: function(error) { reject(error); }, ontimeout: function() { reject(new Error('Request timed out')); } }); }); } // Get Content Type Function function getContentType(response) { const contentTypeHeader = response.responseHeaders.split('\n').find(header => header.toLowerCase().startsWith('content-type')); return contentTypeHeader ? contentTypeHeader.split(':')[1].trim().split(';')[0] : ''; } // Check if Content Type is Allowed function isContentTypeAllowed(contentType) { if (settings.contentTypes.include.length > 0 && !settings.contentTypes.include.includes(contentType)) { return false; } if (settings.contentTypes.exclude.length > 0 && settings.contentTypes.exclude.includes(contentType)) { return false; } return true; } // Evaluate Content Quality Function function evaluateContentQuality(text) { const wordCount = text.split(/\s+/).length; return wordCount; } // Classify Keywords Function function classifyKeywords(text) { const keywords = { '교육': ['학교', '교육', '학생', '교수', '강의'], '기술': ['기술', '소프트웨어', '하드웨어', '프로그래밍', '개발'], '뉴스': ['뉴스', '속보', '기사', '보도'], '엔터테인먼트': ['영화', '음악', '연예', '게임', '드라마'], '스포츠': ['축구', '야구', '농구', '경기', '토너먼트'] // 추가 키워드 및 카테고리 }; for (const [category, kws] of Object.entries(keywords)) { if (kws.some(kw => text.includes(kw))) { return category; } } return '기타'; } // CSV Download Function function downloadCSV() { if (data.length === 0) { log('다운로드할 데이터가 없습니다.', 'warning'); return; } const csvRows = [ ["사이트 이름", "주소", "설명", "분류", "품질점수"] ]; data.forEach(d => { csvRows.push([ `"${escapeCSV(d.name)}"`, `"${escapeCSV(d.url)}"`, `"${escapeCSV(d.description)}"`, `"${escapeCSV(d.category)}"`, `"${d.quality}"` ].join(",")); }); const csvContent = "data:text/csv;charset=utf-8," + csvRows.join("\n"); const encodedUri = encodeURI(csvContent); const link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "data.csv"); document.body.appendChild(link); link.click(); document.body.removeChild(link); log('CSV 파일이 다운로드되었습니다.', 'success'); } // JSON Download Function function downloadJSON() { if (data.length === 0) { log('다운로드할 데이터가 없습니다.', 'warning'); return; } const jsonContent = JSON.stringify(data, null, 2); const blob = new Blob([jsonContent], { type: "application/json" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", "data.json"); document.body.appendChild(link); link.click(); document.body.removeChild(link); log('JSON 파일이 다운로드되었습니다.', 'success'); } // CSV Escaping Function function escapeCSV(str) { if (!str) return ''; return str.replace(/"/g, '""'); } // Table Filtering Function function filterTable(keyword) { $('#data-table-body tr').each(function() { const rowText = $(this).text().toLowerCase(); if (rowText.includes(keyword.toLowerCase())) { $(this).show(); } else { $(this).hide(); } }); } // URL Validation Function function isValidURL(url) { try { new URL(url); return true; } catch (_) { return false; } } // Determine Total Pages Function function determineTotalPages() { // Logic to determine total pages can be added here return settings.maxPages; } // Delay Function function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Initialize Function function init() { createUI(); if (isCrawling) { log('크롤링이 이전에 중단된 상태에서 다시 시작됩니다.', 'info'); setButtonStates(); crawlPage(currentDepth); } else { log('크롤러가 초기화되었습니다.', 'info'); } } // Page Load Event window.addEventListener('load', init); // Extract Links for Deeper Crawling function extractLinks(pageDoc) { const links = []; const anchorTags = pageDoc.querySelectorAll('a[href]'); anchorTags.forEach(a => { let href = a.getAttribute('href'); if (href.startsWith('/url?q=')) { href = new URLSearchParams(href.substring(7)).get('q'); } if (isValidURL(href)) { links.push(href); } }); return links; } // Detect Page Language async function getPageLanguage(url) { try { const response = await GM_xmlhttpRequestPromise(url); const pageHtml = response.responseText; const parser = new DOMParser(); const pageDoc = parser.parseFromString(pageHtml, 'text/html'); const lang = pageDoc.documentElement.lang || ''; return lang.split('-')[0]; } catch (error) { log(`언어 감지 실패: ${url} - ${error.message}`, 'error'); return ''; } } // Schedule Crawling Function function scheduleCrawling() { if (!settings.schedule.enabled) return; const [hours, minutes] = settings.schedule.startTime.split(':').map(Number); const now = new Date(); const start = new Date(); start.setHours(hours, minutes, 0, 0); if (start < now) { start.setDate(start.getDate() + 1); } const firstDelay = start - now; setTimeout(() => { startCrawling(); setInterval(() => { if (!isCrawling) { startCrawling(); } }, settings.schedule.interval); }, firstDelay); log(`크롤링 스케줄이 설정되었습니다. 시작 시간: ${settings.schedule.startTime}, 간격: ${settings.schedule.interval / 1000}초`, 'info'); } // Utility: Capitalize Function function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } })();Key Enhancements Explained:
-
Collapsible Sections in Settings:
- Purpose: To organize settings into manageable sections, improving user experience.
- Implementation: Added buttons with the
collapsibleclass that toggle the visibility of their corresponding content sections.
-
Per Search Engine Settings:
- Purpose: To allow users to customize settings for each search engine individually, enhancing control and flexibility.
- Implementation: Modified
searchEnginesindefaultSettingsto include anenabledflag and a placeholder forspecificSettings. Each search engine now has its own collapsible section in the UI where specific settings can be added later.
-
Advanced Filtering Options:
- Purpose: To provide users with more granular control over the crawling process, such as filtering by date range, region, and enabling/disabling safe search.
- Implementation: Added an Advanced Filtering collapsible section with dropdowns and checkboxes for these options.
-
Reset Settings Functionality:
- Purpose: To allow users to quickly revert to default settings if needed.
- Implementation: Added a "Reset Settings" button that clears all user-defined settings and restores defaults after a confirmation prompt.
-
Improved Search Result Extraction:
- Purpose: To make the crawler more robust against changes in search engine page structures and to ensure more reliable data extraction.
- Implementation: Enhanced the
extractSearchResultsfunction with better selectors and fallback mechanisms. Additionally, added checks to ensure that only valid URLs are processed.
-
Dynamic UI Updates for Search Engines:
- Purpose: To show or hide engine-specific settings based on whether a search engine is enabled.
- Implementation: Added event listeners to search engine checkboxes that toggle the visibility of their corresponding settings sections.
-
Error Handling Enhancements:
Additional Recommendations:
-
Captcha Handling: Some search engines employ captchas to prevent automated access. Implementing a captcha-solving mechanism or notifying the user to solve captchas manually can enhance the crawler’s effectiveness.
-
Proxy Management: To avoid IP blocking, integrating a proxy rotation mechanism can distribute requests across multiple IP addresses.
-
Queue Management: Implementing a more sophisticated queue for managing URLs to crawl (e.g., prioritizing based on relevance) can improve crawling efficiency.
-
Data Storage Optimization: Storing large amounts of crawled data can quickly consume browser storage. Consider batching data storage or integrating with external storage solutions if necessary.
-
User Notifications: Implementing notifications or status updates can keep users informed about the crawler’s progress and any issues encountered.
Conclusion
With these enhancements, your Advanced Web Crawler script is now more flexible, user-friendly, and robust. Users have greater control over the crawling process with detailed settings, and the crawling logic is improved to handle various scenarios more effectively. Remember to test the script thoroughly across different search engines to ensure reliability and to make further adjustments based on specific requirements.
Feel free to reach out if you need further assistance or more specific features!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.