Christmas Pikachu 네이버 날씨 크롤링해서 현재 지역 날씨 조회하기
개발일지/자바

네이버 날씨 크롤링해서 현재 지역 날씨 조회하기

ZI_CO 2023. 12. 22.

 

 

package crwaling;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Crw {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("0. 프로그램 종료");
			System.out.print("동네이름 입력 >>> ");
			String input = sc.next();
			if(input.equals("0")) {
				break;
			}
			String encodedString;
			try {
				// 디코딩된 문자열
				encodedString = URLEncoder.encode(input, StandardCharsets.UTF_8.toString());
				// URL 인코딩

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String url = "https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=" + input + "날씨";

			Document doc = null;

			try {
				doc = Jsoup.connect(url).get();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Elements elems = doc.select("._today:has(span.blind:contains(현재 온도))"); //
			String currentTemperature = null;
			for (Element todayElement : elems) {
				 currentTemperature = todayElement.select("span.blind:contains(현재 온도)").first().nextSibling()
						.toString().trim();
				System.out.println("현재 온도: " + currentTemperature);
			}
			double nowTemp = Double.parseDouble(currentTemperature);
			if(nowTemp < -5.0) {
				System.out.println("==> 패딩입으세요\n");
			}else {
				System.out.println("==> 버스 / 지하철에서 사우나 체험가능\n");
			}
			Elements elements = doc.select("dl.summary_list div.sort:has(dt.term:contains(체감)) dd.desc");

			// 선택된 요소의 텍스트 출력
			String perceivedTemperature = null;
			for (Element element : elements) {
				perceivedTemperature = element.text().replace("°", "");
				System.out.println("체감 온도: " + perceivedTemperature);
			}
			
			double nowperceivedTemp = Double.parseDouble(perceivedTemperature);
			if(nowperceivedTemp < (-10.0)) {
				System.out.println("==> 귀가 뜯겨나가요\n");
			}else {
				System.out.println("==> 손이 시려워요\n");
			}
		}

	}

}

댓글