나는 항상 인터넷에 대해 궁금했습니다. 나는 크롤러를 쓰는 것에 대해 생각했지만 그것을 구현하기에는 너무 게으르다. 나는 이것이 매우 번거로운 일이라고 느꼈다. 작은 오류가 발생하면 시간 낭비였습니다.
나중에, 나는 일찍 보증을 주었기 때문에 먼저 구현하고 단순성으로 시작하고 천천히 기능을 추가하고 시간이있는 경우 기능을 구현하고 언제든지 코드를 최적화해야한다고 생각했습니다.
아래는 지정된 웹 페이지를 크롤링하고 저장하는 간단한 구현입니다. 실제로,이를 구현하는 방법에는 여러 가지가 있습니다. 이 기능의 몇 가지 구현이 천천히 있습니다.
URLConnection 크롤링 구현
패키지 html; import java.io.bufferedReader; import java.io.fileoutputStream; import java.io.fileWriter; import java.io.ioException; import java.io.inputStreamReader; import java.io.outputStreamwriter; import java.net.mormortecment; java.net.url; import java.net.urlconnection; public class spider {public static void main (string [] args) {String filepath = "d : /124.html"; 문자열 url_str = "http://www.hao123.com/"; url url = null; {url = new url (url_str); } catch (marlomedurlexception e) {e.printstacktrace (); } 문자열 charset = "utf-8"; int sec_cont = 1000; {urlConnection url_con = url.openConnection (); url_con.setdooutput (true); url_con.setreadtimeout (10 * sec_cont); url_con.setRequestProperty ( "사용자 에이전트", "Mozilla/4.0 (호환성; MSIE 7.0; Windows NT 5.1)"); inputStream htm_in = url_con.getInputStream (); 문자열 htm_str = inputStream2string (htm_in, charset); savehtml (filepath, htm_str); } catch (ioexception e) {e.printstacktrace (); }} /** * 메소드 : savehtml * 설명 : 파일에 문자열 저장 * @param filepath * 저장 해야하는 파일 경로 * @param str * string saveed * /public static void savehtml (문자열 filepath, string) {try { / * @suppresswarnings ( "resource") filewriter fw = new filewrriter (filepath); fw.write (str); fw.flush ();*/ outputStreamwriter outs = new outputStreamWriter (new FileOutputStream (Filepath, True), "UTF-8"); outs.write (str); System.out.print (str); outs.close (); } catch (ioException e) {System.out.println ( "Save HTML의 오류 ..."); e.printstacktrace (); }} / ** * 메소드 : inputStream2string * 설명 : 입력 스트림을 문자열로 만듭니다 * @param in_st * inputStream * @param charset * value의 인코더 * @throws ioexception * / public string inputstream2string (inputstream in_st, string) ioexemention {brucedreder ch strows {inputstream in_st, string). bufferedReader (new inputStreamReader (in_st, charset)); StringBuffer res = new StringBuffer (); 문자열 line = ""; while ((line = buff.readline ())! = null) {res.append (line); } return res.toString (); }}구현 과정에서 크롤링 된 웹 페이지의 중국어 코드의 문제는 비교적 귀찮은 일입니다.
httpclient 크롤링 구현
httpclient는 웹 페이지를 크롤링 할 때 많은 문제가 발생했습니다. 첫째, Httpclient에는 두 가지 버전이 있으며, 하나는 내장되어 있고 다른 하나는 Apache의 오픈 소스 프로젝트입니다. Sun이 내장되어 있지 않은 것으로 보이므로 구현하지는 않았지만 Apache 오픈 소스 프로젝트를 채택했습니다 (나중에 언급 된 httpclient는 Apache의 오픈 소스 버전을 말합니다). 둘째, httpclient를 사용할 때 최신 버전은 이전 버전과 다릅니다. httpclient 4.x 버전 후에는 가져온 패키지가 다릅니다. 인터넷에서 발견되는 많은 부분은 HTTPClient 3.X 버전이므로 최신 버전을 사용하는 경우 도움말 파일을 보는 것이 좋습니다.
Eclipse를 사용하고 있으며 참조 패키지를 가져 오려는 환경을 구성해야합니다.
먼저, httpclient를 다운로드하십시오. 주소는 http://hc.apache.org/downloads.cgi입니다. httpclient 버전 4.2를 사용하고 있습니다.
그런 다음, 꺼짐, Commons-Codec-1.6.jar, commons-logging-1.jar, httpclient-4.2.5.jar, httpcore-4.2.4.jar /lib 폴더의 httpcore-4.2.5.jar를 찾으십시오 (버전 번호는 다운로드 된 버전에 따라 다르며 다른 JAR 파일이 있으므로 시간에 사용할 수없는 다른 JAR 파일이 있습니다).
마지막으로 위의 JAR 파일을 클래스 경로에 추가하십시오. 즉, 프로젝트 파일 => bulid path => 빌드 경로 구성 => 외부 JAR을 추가 한 다음 위의 패키지를 추가하십시오.
또 다른 방법은 위의 패키지를 프로젝트 폴더 아래의 lib 폴더에 직접 복사하는 것입니다.
구현 코드는 다음과 같습니다.
패키지 html; import java.io.bufferedReader; import java.io.fileoutputStream; import java.io.ioException; import java.io.inputStreamReader; import java.io.inputStreamReader; import java.io.outputStreamWriter; import org.apache.http.httpentity; org.apache.http.httpresponse; import org.apache.http.client.*; import org.apache.http.client.method.httpget; import org.apache.http.impl.client.defaulthtttpclient; public spiderhttpclient {public spiderhttpclient {] // todo 자동 조성 메소드 Stub String url_str = "http://www.hao123.com"; 문자열 charset = "utf-8"; 문자열 filepath = "d : /125.html"; httpclient hc = 새로운 defaulthttpclient (); httpget hg = new httpget (url_str); httpresponse 응답 = hc.execute (hg); httpentity entity = response.getentity (); 입력 스트림 htm_in = null; if (entity! = null) {system.out.println (entity.getContentLength ()); htm_in = entity.getContent (); 문자열 htm_str = inputStream2string (htm_in, charset); savehtml (filepath, htm_str); }} /** * 메소드 : savehtml * 설명 : 파일에 문자열 저장 * @param filepath * 저장 해야하는 파일 경로 * @param str * string saveed * /public static void savehtml (문자열 filepath, string) {try { / * @suppresswarnings ( "resource") filewriter fw = new filewrriter (filepath); fw.write (str); fw.flush ();*/ outputStreamwriter outs = new outputStreamWriter (new FileOutputStream (Filepath, True), "UTF-8"); outs.write (str); outs.close (); } catch (ioException e) {System.out.println ( "Save HTML의 오류 ..."); e.printstacktrace (); }} / ** * 메소드 : inputStream2string * 설명 : 입력 스트림을 문자열로 만듭니다 * @param in_st * inputStream * @param charset * value의 인코더 * @throws ioexception * / public string inputstream2string (inputstream in_st, string) ioexemention {brucedreder ch strows {inputstream in_st, string). bufferedReader (new inputStreamReader (in_st, charset)); StringBuffer res = new StringBuffer (); 문자열 line = ""; while ((line = buff.readline ())! = null) {res.append (line); } return res.toString (); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.