[Java] Crolling 크롤링 코드

Jeini·2023년 1월 27일
0

📌 Code list

목록 보기
49/55
post-thumbnail
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JOptionPane;

public class Crolling {
	public static void getSource() {
		String defaultURL = "https://finance.naver.com/item/main.naver?code=";
		String urlString;
		
        do {
			urlString = JOptionPane.showInputDialog("코드번호");
		} while(urlString == null || urlString.trim().length() == 0);

		HttpURLConnection con = null;
        
		try {
			URL url = new URL(defaultURL + urlString);
			con = (HttpURLConnection)url.openConnection();
			String msg = "응답코드 이상 : ";
			int responseCode = con.getResponseCode();
			
            if(responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
				try(
						InputStream is = con.getInputStream();
						BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
						FileWriter fw = new FileWriter("result.html");
				) {
					String line = null;
					StringBuffer buf = new StringBuffer();
					while((line = br.readLine()) != null) {
						buf.append(line + "\n");
					}
					fw.write(buf.toString());
					fw.flush();
					msg = "작업완료";
				}
			} else {
				msg += responseCode;
			}
			JOptionPane.showMessageDialog(null, msg);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try{
				con.disconnect();
			} catch(Exception e) {}
		}
	}
	public static void getPrice() {
		//파일을 읽어와서 String가지고 IndexOf, substring활용해서 문자열발췌
		FileInputStream fis = null;

	public static void main(String[] args) {
		getSource();
		getPrice();
	}
}
profile
Fill in my own colorful colors🎨

0개의 댓글