
기온 부분의 데이터를 스크래핑할 것이기 때문에 기온 부분을 우 클릭 후 검사 버튼을 눌러 위치를 확인한다.
id가 my-tchart인 저 부분이 우리가 추출해야 하는 그래프의 데이터임을 알 수 있다.driver 객체에 응답을 담고 이 객체에서 id가 my-tchart인 부분을 추출해야 한다는 것을 알 수 있다.스크래핑을 하기 위한 라이브러리를 호출해야 한다. (이 내용은 3, 4에 더 자세하게 나와 있다.)driver 객체를 생성한 후 driver 객체에 스크래핑 할 웹 페이지에 보낸 응답을 담는다.동적인 페이지로 .implicitly_wait()를 통해 기다림을 주어야 한다. 그렇지 않으면 요소를 찾을 수 없다는 오류가 발생한다..find_element를 통해 id가 my-tchart인 요소를 찾아 준다.from selenium import webdriver
from selenium.webdriver import ActionChains
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.weather.go.kr/w/weather/forecast/short-term.do")
driver.implicitly_wait(10)
temps = driver.find_element(By.ID, "my-tchart").text
print(temps)
temps를 print 해 보면 다음과 같은 output을 볼 수 있다.
하나의 문자열임에도 줄 바꿈이 일어난다는 것은 문자열 안에 개행이 있음을 알 수 있다. 또한 그래프로 표출해 주기 위해서는 단위인 ℃가 제외되어야 한다.정수(int) 타입이어야 한다.#개행으로 split을 해 주고
#단위를 없애 주고, int로 변환시켜 각각 요소를 리스트에 담는다
temps = [ int(i) for i in temps.replace("℃", "").split("\n")]
#output
#[14, 13, 12, 11, 10, 11, 13, 14, 15, 18, 19, 19, 20, 20, 21, 20, 19, 17, 17]
꺾은 선 그래프로 시각화하기 위해 seaborn 라이브러리를 호출해 준다.꺾은 선 그래프를 더 편하게 볼 수 있도록 x, y label명, title명, y축의 최솟값과 최댓값 범위, 그래프 크기를 설정해 주기 위해 matplotlib.pyplot 라이브러리 역시 호출해 준다..lineplot(x=x 값 리스트, y=y 값 리스트) 함수를 통해 꺾은 선 그래프(Line Plot)을 그려 준다.import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize = (20, 10)) #그래프 캔버스의 크기는 그래프가 그려지기 전에 먼저 설정해 주어야 한다.
plt.ylim(min(temps), max(temps)) #기온의 최솟값과 최댓값을 y축의 한계점으로 둔다.
plt.title("Expected Temperature from now on") #title 지정
plt.ylabel("Temperature(℃)") #y축 이름 지정
sns.lineplot(x=[i for i in range(len(temps))], y=temps) #lineplot을 그려 준다.
plt.show()
결과 값