|
|
게시됨 2014. 11. 30. 오후 4:56:56
|
|
|
|

[mw_shl_code=java, true]/** * @author Jack.Wang
* */ java.io.BufferedReader를 import; import java.io.InputStreamReader; java.net.URL 가져오기; import java.util.ArrayList; java.util.HashMap을 import; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.regex.Matcher; import java.util.regex.Pattern;
웹 크롤러 검색 public class SearchCrawler는 Runnable {
/* * disallowListCache 캐시 로봇은 검색된 URL을 허용하지 않습니다. 로봇 프로토콜은 웹사이트의 루트 디렉터리에 robots.txt 파일을 설정합니다. * 사이트 내 제한된 검색이 가능한 페이지를 지정함. * 검색 프로그램은 검색 중에 이 영역들을 건너뛰어야 하며, 다음은 robots.txt 예시입니다: * # http://somehost.com/ 사용자 에이전트를 위한 robots.txt: * 금지: /cgi-bin/ * 등록 금지: /등록 # 등록 페이지에서 로봇 금지 * 불허용: /로그인 */
private HashMap<String, ArrayList<String>> disallowListCache = new HashMap<String, ArrayList<String>>(); ArrayList<String> errorList = new ArrayList<String>(); 오류 메시지 ArrayList<String> 결과 = new ArrayList<String>(); 검색 결과 문자열 startUrl; 검색을 시작하는 출발점입니다 int maxUrl; 처리된 최대 URL 수 String searchString; 검색할 문자열 불리언 케이스민감 = false; 대소수에 구분할지에 대한 의지 불리언 limitHost = false; 제한된 호스트 내에서 검색할지?
public SearchCrawler(String startUrl, int maxUrl, String searchString) { this.startUrl = startUrl; this.maxUrl = maxUrl; this.searchString = searchString;
}
public ArrayList<String> getResult() { 반환 결과;
}
public void run() { // 검색 스레드 시작 crawl(startUrl, maxUrl, searchString, limitHost, caseSensitive);
}
URL 서식 감지 private URL verifyUrl(String URL) { 처리되는 것은 HTTP URL뿐입니다. if (!url.toLowerCase().startsWith("http://")) null을 반환; URL verifiedUrl = null; 시도해 { verifiedUrl = 새 URL(url); } catch (예외 e) { null을 반환; } return verifiedUrl;
}
로봇이 주어진 URL에 접근을 허용하는지 감지합니다. private boolean isRobotAllowed(URL urlToCheck) { String host = urlToCheck.getHost().toLowerCase(); RUL을 주는 호스트를 구하세요 System.out.println("host="+host);
호스트에서 검색을 허용하지 않는 URL 캐시를 확보하세요 ArrayList<String> disallowList = disallowListCache.get(host);
아직 캐시가 없다면 다운로드해서 캐시하세요. 만약 (disallowList == null) { disallowList = new ArrayList<String>(); 시도해 { URL robotsFileUrl = 새 URL("http://" + 호스트 + "/robots.txt"); BufferedReader = 새로운 BufferedReader( 새로운 InputStreamReader(robotsFileUrl.openStream());
로봇 파일을 읽어 접근 금지 경로 목록을 만드세요. 스트링 라인; while ((line = reader.readLine()) != null) { if (line.indexOf("Disallow:") == 0) {// "Disallow:"를 포함하나요? 문자열 disallowPath = line.substring("Disallow:" .length()); 접근 금지 경로 확인
주석을 확인하세요. int commentIndex = disallowPath.indexOf("#"); 만약 (commentIndex != -1) { disallowPath = disallowPath.substring(0, commentIndex); 댓글을 삭제하세요 }
disallowPath = disallowPath.trim(); disallowList.add(disallowPath); } }
이 호스트가 접근할 수 없는 캐시 경로들. disallowListCache.put(host, disallowList); } catch (예외 e) { 진짜로 반환; 웹사이트의 루트 디렉터리에는 robots.txt 파일이 없고, true로 반환됩니다 } }
String file = urlToCheck.getFile(); System.out.println("File getFile()="+file); (정수: i = 0; < disallowList.size(); i++) { string disallow = disallowList.get(i); if (file.startsWith(disallow)) { return false; } }
진짜로 반환;
}
private String downloadPage(URL pageUrl) { 시도해 { 읽기 위해 URL로 연결하세요. BufferedReader 리더 = new BufferedReader(new InputStreamReader( pageUrl.openStream()));
페이지를 버퍼로 읽으세요. 스트링 라인; StringBuffer pageBuffer = new StringBuffer(); while ((line = reader.readLine()) != null) { pageBuffer.append(line); }
return pageBuffer.toString(); } catch (예외 e) { }
null을 반환;
}
URL에서 "www" 항목을 제거하세요 private String removeWwwFromUrl(String url) { int 인덱스 = url.indexOf("://www."); 만약 (지수 != -1) { url.substring(0, index + 3) + url.substring(index + 7); }
return(URL);
}
페이지를 분석하고 링크를 찾아보세요 private ArrayList<String> retrieveLinks(URL pageUrl, String pageContents, HashSet crawledList, boolean limitHost) { 정규 표현식으로 링크의 일치 패턴을 합성합니다. Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*"?(. *?) [\"|>]", Pattern.CASE_INSENSITIVE); 매처 m = p.매처(pageContents);
ArrayList<String> linkList = new ArrayList<String>(); 반면 (m.find()) { String link = m.group(1).trim();
만약 (link.length() < 1) { 계속하세요; }
이 페이지 링크는 건너뛰세요. if (link.charAt(0) == '#') { 계속하세요; }
if (link.indexOf("mailto:") != -1) { 계속하세요; }
if (link.toLowerCase().indexOf("javascript") != -1) { 계속하세요; }
if (link.indexOf("://") == -1) { 만약 (link.charAt(0) == '/') {//가 절대적으로 처리한다면 링크 = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + 링크; } 그렇지 않으면 { String file = pageUrl.getFile(); if (file.indexOf('/') == -1) {// 상대 주소를 처리합니다 링크 = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + "/" + 링크; } 그렇지 않으면 { String path = file.substring(0, file.lastIndexOf('/') + 1); 링크 = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + 경로 + 링크; } } }
int 인덱스 = link.indexOf('#'); 만약 (지수 != -1) { 링크 = link.substring(0, 인덱스); }
링크 = removeWwwFromUrl(링크);
URL verifiedLink = verifyUrl(link); 만약 (verifiedLink == null) { 계속하세요; }
/* 호스트를 제한할 경우, 기준에 부합하지 않는 URL은 제외하세요 */ 만약 (limitHost && !pageUrl.getHost().toLowerCase().equals( verifiedLink.getHost().toLowerCase())) { 계속하세요; }
이미 처리된 링크는 건너뛰세요. if (crawledList.contains(링크)) { 계속하세요; }
linkList.add(링크); }
return(링크리스트);
}
다운로드한 웹페이지의 내용을 검색하여 해당 페이지에 지정된 검색 검색어가 있는지 확인하세요
private boolean searchStringMatches(String pageContents, String searchString, boolean caseSensitive) { 문자열 검색Contents = pageContents; 만약 (!caseSensitive) {// 대문자에 민감하지 않으면 searchContents = pageContents.toLowerCase(); }
패턴 p = Pattern.compile("[\\s]+"); String[] terms = p.split(searchString); (정수: i = 0; 저는 terms.length를 <합니다; i++) { 만약 (caseSensitive) { if (searchContents.indexOf(terms) == -1) { return false; } } 그렇지 않으면 { if (searchContents.indexOf(terms.toLowerCase()) == -1) { return false; } } }
진짜로 반환;
}
실제 탐색 연산을 수행하세요 public ArrayList<String> crawl(String startUrl, int maxUrls, String searchString, boolean limithost, boolean caseSensitive) {
HashSet<String> crawledList = new HashSet<String>(); LinkedHashSet<String> toCrawlList = new LinkedHashSet<String>();
만약 (maxUrls < 1) { errorList.add("유효하지 않은 최대 URL 값."); System.out.println("유효하지 않은 최대 URL 값."); }
만약 (searchString.length() < 1) { errorList.add("검색 문자열이 빠진 경우."); System.out.println("누락된 검색 문자열"); }
if (errorList.size() > 0) { System.out.println("err!!"); errorList를 반환; }
시작 URL에서 www를 이동하세요 startUrl = removeWwwFromUrl(startUrl);
toCrawlList.add(startUrl); while (toCrawlList.size() > 0) {
만약 (maxUrls != -1) { if (crawledList.size() == maxUrls) { 브레이크; } }
목록 맨 아래에 URL을 확인하세요. String url = toCrawlList.iterator().next();
크롤 목록에서 URL을 제거하세요. toCrawlList.remove(url);
문자열 URL을 URL 객체로 변환하세요. URL verifiedUrl = verifyUrl(url);
로봇이 접근할 수 없다면 URL을 건너뛰세요. if (!isRobotAllowed(verifiedUrl)) { 계속하세요; }
처리된 URL을 crawledList에 추가하세요 crawledList.add(url); 문자열 페이지 내용 = 다운로드페이지(verifiedUrl);
if (pageContents != null && pageContents.length() > 0) { 페이지에서 유효한 링크를 받으세요 ArrayList<String> links = retrieveLinks(verifiedUrl, pageContents, crawledList, limitHost);
toCrawlList.addAll(링크);
if (searchStringMatches(pageContents, searchString, caseSensitive)) { result.add(URL); System.out.println(url); } }
} 반환 결과;
}
주요 기능 public static void main(String[] args) { SearchCrawler crawler = 새로운 SearchCrawler("http://www.itsvse.com/", 100,"Delver_Si"); 스레드 검색 = 새로운 스레드(크롤러); System.out.println("검색 시작..."); System.out.println("result:"); search.start(); 시도해 { search.join(); } catch (InterruptedException e) { TODO 자동 생성 캐치 블록 e.printStackTrace(); }
}
} [/mw_shl_code]
|
-
1.png
(100.02 KB, 다운로드 횟수: 591)
-
2.png
(72.18 KB, 다운로드 횟수: 596)
-
3.png
(188.46 KB, 다운로드 횟수: 606)
이전의:PHP는 상위 100W 웹사이트의 82.2%를 차지합니다다음:자바 에디션 웹 소스 코드 뷰어
|