Urlib 네이버 날씨 크롤링 2022 개정판 예제
파이썬 크롤링

Urlib 네이버 날씨 크롤링 2022 개정판 예제

Mr.Zee 2022. 4. 4.

파이썬에서 간단하게 네이버 날씨 및 기상청 날씨를 가져올 수 있는 예제입니다.

* 본 예제 및 사용 인터프리터는 파이참 (pycharm) + Python 3.8 버전입니다.

 

완제 코드는 문서 가장 맨 아래에 있습니다. 목차 참고.

 

#Python Korea Weather Crawling 2022 Revise
#https://mustzee.tistory.com

import datetime
import urllib
from bs4 import BeautifulSoup
import urllib.request as req

now = datetime.datetime.now()
nowDate = now.strftime('%Y년 %m월 %d일 %H시 %M분 입니다.')

print("\n   Python Weather Crawling 2022 Revise\n ")
print('   Current Datetime, ' + nowDate)
print('   오늘의 날씨 정보입니다.\n')

# 기상청에서 데이터를 가져옵니다.
url = "http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp"
res = req.urlopen(url)
# res = req.urlopen("http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp")
soup = BeautifulSoup(res, "html.parser")
# Html 수프를 떠요. 우리가 지정해준 url을 파이썬이 대신 열어서 해당 html 파일을 파싱 (복사)해옵니다.

title = soup.find("title").string
# html 구문 분석 결과 타이틀을 가져올거에요

weather_info = soup.find("wf").string
print(title)
print(weather_info)
# 좀더 깔끔하게 표현하려면 print 함수내에 내장된 sep 기능과 텍스트 치환기능 을 활용해요
# print(weather_info.replace("<br />","\n "),sep='\n')


#네이버 날씨 크롤링
# Phase1 Seoul Weather Crawling

webpage = urllib.request.urlopen('https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query=%EC%84%9C%EC%9A%B8%EB%82%A0%EC%94%A8')

soup = BeautifulSoup(webpage, 'html.parser')
temps = soup.find('div','temperature_text')
summary = soup.find('p','summary')
# print(temps)
print("서울 "+temps.text.strip())
# print(summary)
print(summary.text.strip())

시도해보면 아쉽게도 네이버 크롤링 예제 부분은 에러가 발생할 가능성이 높습니다.

 

왜 그럴까요?

 

Python 3.8 버전 실행 결과

완전 자세히까지 들어가진 않겠지만 https로 된 웹사이트를 크롤링하기 위해서는 우리가 사용하는 라이브러리인 python urlib에 ssl 기능을 좀 더 보강해줘야 합니다.

이런 에러가 뜨면 일단 구글에다가 저 에러 코드 자체를 전체 붙여 넣기 해보면 좀 더 빠르게 해결책을 찾아볼 수 있어요.

 

찾아보니 pip에 ssl 버전을 업데이트하라고 합니다.

 

먼저 터미널에서 우리의 인스톨 도우미 pip 버전을 업그레이드해줍니다.

명령어는

pip isntall --upgrade pip

라고 써주시고 엔터를 눌러주세요.

버전 업그레이드를 한지 얼마 안 되신 분들은 넘어가도 상관없습니다~

 

컨텐츠 전문 보기>>

https://epix.kr/urlib-%eb%84%a4%ec%9d%b4%eb%b2%84-%eb%82%a0%ec%94%a8-%ed%81%ac%eb%a1%a4%eb%a7%81-2023-%ea%b0%9c%ec%a0%95%ed%8c%90-%ec%98%88%ec%a0%9c/

 

댓글

💲 추천 글