Programming
No. | 401 |
Name. | swindler |
Subject. | HTML Parsing Package |
Main Cate. | Java |
Sub Cate. | |
Date. | 2007-10-30 16:37 |
Hit. | 3365 (211.36.27.8) |
File. | |
이런 클래스도 있다. 만족스럽지는 않지만... 사실 Java에서는 URLConnection, TCP/IP Connection 같은 부분들이 제일 아쉽다 import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.HTML; import java.io.InputStreamReader; import java.net.URL; import java.net.HttpURLConnection; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.parser.ParserDelegator; public class Par { //파서는 콜백 형식으로 되어 있다. 각 태그가 들어 올때 적절한 메소드가 호출됨 private class CallbackHandler extends HTMLEditorKit.ParserCallback { //태그가 시작할 때 호출 되는 메소드 public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos) { //<A href 인 경우... A태그를 찾는다... if (tag == HTML.Tag.A) { //System.out.println(a.getAttribute(javax.swing.text.html.HTML.Attribute.HREF)); } if (tag == HTML.Tag.META) { System.out.println(a.getAttribute(javax.swing.text.html.HTML.Attribute.CONTENT)); } if (tag == HTML.Tag.SCRIPT) { System.out.println("-----------script start"); } } //태그가 시작할 때 호출 되는 메소드 public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet a, int pos) { //<A href 인 경우... A태그를 찾는다... if (tag == HTML.Tag.A) { //System.out.println(a.getAttribute(javax.swing.text.html.HTML.Attribute.HREF)); } if (tag == HTML.Tag.META) { System.out.println(a.getAttribute(javax.swing.text.html.HTML.Attribute.CONTENT)); System.out.println("charset : "+a.getAttribute("charset")); } if (tag == HTML.Tag.SCRIPT) { System.out.println("-----------script start"); } } //태그가 시작할 때 호출 되는 메소드 public void handleEndTag(HTML.Tag tag, int pos) { if (tag == HTML.Tag.SCRIPT) { System.out.println("-----------script end"); } } //텍스트가 들어올때 호출되는 메소드 public void handleText(char[] data, int pos) { //System.out.println(data); } } public void parse(String str) { String content = null; try { //입력받은 URL에 연결하여 InputStream을 통해 읽은 후 파싱 한다. URL url = new URL(str); HttpURLConnection con = (HttpURLConnection)url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream(),"euc-kr"); new ParserDelegator().parse(reader, new CallbackHandler(), true); con.disconnect(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Par parser = new Par(); if(args.length==1) parser.parse(args[0]); else parser.parse("http://www.netien.com/home/kor/business/portfolio/portfolio01.asp?globalmenu=2&localmenu=11"); } } [바로가기 링크] : http://coolx.net/cboard/develop/401 |
|
|
|
[Modify] [Delete] | [Reply] [List] |