크롤링해서 현재 날씨와 기온을 가져와보자..
(아래 문장은 chatgpt api를 이용해서 만든건데.. 현재 서비스중인 chatGPT3.5보다 더 형편없는듯한 답변이..)
//크롤링
implementation 'org.jsoup:jsoup:1.15.3'
크롤링을 위해 jsoup 라이브러리를 사용한다.
build.gradle 파일에 dependencies에 위 코드를 추가한다.
@Getter
@Builder
public class Weather {
private String condition;
private String temperature;
}
날씨와 온도 정보를 저장하기 위해서 Weather클래스를 정의했다.(예시)
그리고 WeatherService라는 서비스 클래스를 만들었고, getWeather메소드 내에서 크롤링을 하도록 코드를 작성했다.
@Service
public class WeatherService {
String WeatherURL = "https://weather.naver.com/today";
public Weather getWeather() throws IOException {
Document document = Jsoup.connect(WeatherURL).get();
Elements content = document.select(".weather_area");
Weather weather = Weather.builder()
.condition(content.select(".weather").text()) // 날씨
.temperature(content.select(".current").text().replaceAll("[^0-9.]", "")) // 숫자와 소수점만 남기고 제거) //온도
.build();
return weather;
}
}
이 코드가 어떻게 작성되었는지 보자..
String WeatherURL = "https://weather.naver.com/today";
이것은 크롤링 대상이 되는 url주소이다.
https://weather.naver.com/today 이 주소로 접속하면 오늘의 날씨를 볼 수 있다.
접속하면 나오는 화면이다.
우리는 동그라미 친 영역으로부터 날씨(흐림)정보와 온도(33.2')를 가져오면 된다.
F12를 누르거나 우클릭->검사 버튼을 누르면 브라우저 우측에 검은색 창이 나온다.
여기서 동그라미친 버튼을 클릭하고, 내가 원하는 정보(여기서는 33.2도라는 온도정보)에 마우스를 클릭하면,
해당하는 html영역을 보여준다.
이것을 보고 html에서 이 영역의 정보를 가져다쓰면 되겠구나 생각할 수 있다.
<div class="weather_area">
<div class="weather_now">
<div class="summary_img ">
<i class="ico_animation _cnLazy" data-ico="ico_animation_wt7" data-ymdt="2023072016"></i>
<strong class="current ">
<span class="blind">현재 온도</span>32.7<span class="degree">°</span>
</strong>
</div>
<p class="summary">
<span class="weather">흐림</span>
<em>어제보다</em> <span class="temperature up">2.2° <span class="blind">높아요</span></span></p>
</div>
...
</div>
여기서 현재 온도 정보는 .weather_area 내부 .current 내부에 있고,
현재 날씨 정보는 .weather_area내부 .weather 내부에 있는것을 알 수 있다.
다시 코드를 보면..
public Weather getWeather() throws IOException {
Document document = Jsoup.connect(WeatherURL).get();
Elements content = document.select(".weather_area");
Weather weather = Weather.builder()
.condition(content.select(".weather").text()) // 날씨
.temperature(content.select(".current").text().replaceAll("[^0-9.]", "")) // 숫자와 소수점만 남기고 제거) //온도
.build();
return weather;
}
document.select()를 이용해서 두 정보를 모두 둘러싸고있는 .weather_area 내부 요소를 선택했고,
Weather 인스턴스를 생성하면서 condition에는 날씨정보를 넣기 위해 content.select(".weather").text()를,
temperature에는 온도정보를 넣기위해 content.select(".current").text()를 했다.
추가로, .current내부에는 "현재 온도 32.7°" 라는 문자열이 있는데, 여기서 32.7이라는 숫자만 뽑아내기 위해 String.replaceAll메소드를 사용했다.
'웹개발' 카테고리의 다른 글
클라우드컴퓨터 MySQL 계정 생성하고 사용하기 (0) | 2023.11.10 |
---|---|
네이버 클라우드 서버 생성 (0) | 2023.09.07 |
ngrok CORS 해결하기 (0) | 2023.08.17 |
ngrok: 로컬 서버를 인터넷에 공개하기 (0) | 2023.08.15 |
chatgpt api를 이용해보다 (0) | 2023.07.20 |
댓글