아름다운 스프4(beautifulsoup4) 만 알고 있던 나에게 Selenium이란 라이브러리를 알아버렸다.
미쳤다. 그저 GOAT.
이말 저말 필요없이 실제로 구현 해보자.
먼저 문제를 제시하니 혹시 selenium을 알고 있으셨던 분들은 직접 한번 구현해보면서 연습하면 좋을 것 같다.
참고로 colab 환경에서하면 이래저래 설정할게 많아서 local이나 jupyter notebook 활용합시다.
이번주 날씨 변화를 그래프로 나타내자!
1. selenium과 webdriver-manager를 설치하고 필요 라이브러리들(webdriver, ChromeDriverManager, By, Keys)을 import 하시오.
2. 네이버 날씨 페이지("https://weather.naver.com/") 를 selenium을 이용하여 창을 여시오.
3. 오늘 최고/최저 온도를 크롤링 하시오.
4. 내일 최고/최저 온도를 크롤링 하시오.
5. 일주일의 최저/최고 온도를 크롤링 하시오.
6. 일주일의 최저/최고 온도를 선 그래프로 나타내시오.
바로 코드부터 공개!!
저는 jupyter notebook에서 실습을 진행 했습니다!!
1. selenium 와 webdriver-manager 설치 및 필요 라이브러리들 import
# 1)
!pip install selenium
!pip install webdriver-manager
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
2. 네이버 날씨 페이지("https://weather.naver.com/") 를 selenium을 이용하여 창 열기
# 2)
url = "https://weather.naver.com/"
ChromeDriverManager().install()
browser = webdriver.Chrome()
browser.get(url)
3. 오늘 최고/최저 온도를 크롤링.
# 3)
def temp_preprocess(temp):
result = []
for i in temp:
if i in '0123456789':
result.append(i)
ans = "".join(result)
return int(ans)
weather_elements = browser.find_elements(By.CLASS_NAME, "day_data")
today = weather_elements[0].text.split('\n')
today_date = today[1]
today_min_temp = temp_preprocess(today[-3])
today_max_temp = temp_preprocess(today[-1])
여기서 temp_preprocess 함수는 온도 텍스트에 온도 외에도 이상한 텍스트들이 같이 들어 있어 전처리 해주기 위해 만들었습니다
4. 내일 최고/최저 온도를 크롤링.
# 4)
tomorrow = weather_elements[1].text.split('\n')
tomorrow_date = tomorrow[1]
tomorrow_min_temp = temp_preprocess(tomorrow[-3])
tomorrow_max_temp = temp_preprocess(tomorrow[-1])
5. 일주일의 최저/최고 온도를 크롤링.
# 5)
week =[]
for weather in weather_elements[2:]:
item = weather.text.split('\n')
if len(item) > 5:
data = { "date" : item[1],
"min_temp" : temp_preprocess(item[-3]),
"max_temp" : temp_preprocess(item[-1])
}
week.append(data)
6. 그래프 구현
# 6)
import matplotlib.pyplot as plt
date = [today_date, tomorrow_date]
min_temperatures = [today_min_temp, tomorrow_min_temp]
max_temperatures = [today_max_temp, tomorrow_max_temp]
for item in week:
date_item = item['date']
min_temp = item['min_temp']
max_temp = item['max_temp']
date.append(date_item)
min_temperatures.append(min_temp)
max_temperatures.append(max_temp)
plt.plot(date, min_temperatures, color='blue', label="min temperature")
plt.plot(date, max_temperatures, color='red', label="max temperature")
plt.title("Min/Max Weather")
plt.ylabel("temperature")
plt.xlabel("date")
plt.legend()
plt.grid(True)
plt.show()
결과
Selenium 함수 정리
Selenium 라이브러리 함수 정리
selenium을 colab에서 실행 해야 하는 경우 부가적인 설정들을 해줘야 한다. colab이 selenium에서 창 여는것 자체를 막고 있다나 뭐라나... 너무 귀찮다... colab pro샀는데 ㅜㅜ 그래서 VSCode같은 local 환경
developerahjosea.tistory.com
'EDA > selenium' 카테고리의 다른 글
STR 자동 예매 후 카톡 보내는 매크로 만들기! (selenium + PyKakao) (0) | 2024.04.10 |
---|---|
selenium 라이브러리 함수 정리 (0) | 2024.04.04 |