2주차 금요일, 10일차 Today I Learned
웹 데이터 크롤 및 분석 (5)
: 시각화 라이브러리 Seaborn으로 스크래핑 결과 시각화하기
✏️ 학습 내용
1. 시각화 라이브러리, Seaborn
seaborn은 matplotlib을 기반으로 하는 시각화 라이브러리이다. 다양한 그래프를 고수준에서 쉽게 그릴 수 있다.
import seaborn as sns
# 꺾은 선 그래프
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
# 막대 그래프
sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])
위 내용과 같이 seaborn 라이브러리로 그래프를 그릴 수 있다.
그리고 matplotlib을 통해서 그래프를 꾸밀 수도 있다.
import matplotlib.pyplot as plt
# 막대 그래프 꾸미기
sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])
plt.title("Bar Plot") # 제목 추가
plt.xlabel("X Label") # x축 설명 추가
plt.ylabel("Y Label") # y축 설명 추가
# 꺾은 선 그래프 꾸미기
plt.figure(figsize = (20, 10)) # 그래프 사이즈 정하기 (그래프 그리기 전에 입력!)
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])
plt.ylim(0, 10) # 그래프의 축의 범위 지정하기
plt.show()
2. 스크래핑 결과 시각화하기
# 기상청 날씨 데이터 가져오기
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
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(5)
temps = driver.find_element(By.ID, "my-tchart").text
temps = [int(i) for i in temps.replace("℃", "").split("\n")]
# 그래프 그리기
import seaborn as sns
import matplotlib.pyplot as plt
plt.ylim(min(temps)-2, max(temps)+2)
plt.title("Expected Temperature from now on")
sns.lineplot(
x = [i for i in range(len(temps))],
y = temps
)
plt.show()
import time
frequency = {}
import requests
from bs4 import BeautifulSoup
for i in range(1, 11):
res = requests.get("https://hashcode.co.kr/?page={}".format(i), user_agent)
soup = BeautifulSoup(res.text, "html.parser")
# 1. ul 태그를 모두 찾기
# 2. 1번 안에 잇는 li 태그의 text를 추출
ul_tags = soup.find_all("ul", "question-tags")
for ul in ul_tags :
li_tags = ul.find_all("li")
for li in li_tags :
tag = li.text.strip()
if tag not in frequency :
frequency[tag] = 1
else :
frequency[tag] += 1
time.sleep(0.5)
from collections import Counter
counter = Counter(frequency)
counter.most_common(10)
import seaborn as sns
x = [elem[0] for elem in counter.most_common(10)] # 태그 이름
y = [elem[1] for elem in counter.most_common(10)] # 횟수
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.title("Frequency of question in Hashcode")
plt.xlabel("Tag")
plt.ylabel("Frequency")
sns.barplot(x=x, y=y)
plt.show()
user_agent 이용하는 이유 :
user_agent 변수는 값을 할당하는 과정에서 사용된다. user_agent는 HTTP 요청 헤더의 일부로, 서버에게 요청을 보내는 클라이언트(웹 스크래퍼)를 식별하기 위한 문자열이다. 보통 사용자 에이전트 문자열은 웹 브라우저 및 버전 정보를 포함하며, 서버는 이를 통해 요청이 어떤 클라이언트에서 왔는지 파악할 수 있다.
requests.get() 메서드를 사용할 때, 웹 스크래퍼가 웹 브라우저처럼 동작하도록 보이기 위해 사용자 에이전트 문자열을 설정하는 것이 일반적이다. 이렇게 하면 웹 서버가 요청을 거부하지 않고, 스크래핑 작업이 더 원할하게 수행된다.
이렇게 설정된 user_agent를 사용하여 웹 스크래핑 요청을 보내면, 서버는 해당 요청을 일반적인 웹 브라우저에서 온 것으로 간주한다.
3. 워드 클라우드 (Wordcloud)
워드 클라우드란 자주 등장하는 텍스트를 중요도나 인기도를 고려하여 표현한 것이다. 무엇이 중요한 키워드인지 시각적으로 표현하여 쉽게 파악할 수 있다.
워드 클라우드를 만들기 위해서는 먼저 자연어 문장에서 키워드를 추출한다. 그리고 해당 키워드가 등장한 빈도를 측정해야 한다. 파이썬에서는 딕셔너리를 이용해 표현할 수 있다. 그리고 앞에서 전처리한 정보와 워드클라우드 라이브러리를 바탕으로 워드클라우드를 생성하면 된다.
1. 자연어 문장에서 키워드 추출
2. 키워드 등장 빈도 측정
3. 워드클라우드 생성
user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
import requests
from bs4 import BeautifulSoup
questions = []
import time
for i in range(1, 6):
res = requests.get("https://hashcode.co.kr/?page={}".format(i), {"User-Agent": user_agent})
soup = BeautifulSoup(res.text, "html.parser")
parsed_datas = soup.find_all("li", "question-list-item")
for data in parsed_datas:
questions.append(data.h4.text.strip())
time.sleep(0.5)
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from collections import Counter
from konlpy.tag import Hannanum
hannanum = Hannanum()
for question in questions :
nouns = hannanum.nouns(question) # 1번 반복할 때 나온 명사
words += nouns # 누적된 명사들
counter = Counter(words)
wordcloud = WordCloud(
font_path="...",
background_color="white"
width=1000,
height=1000
)
img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)
☁️ 소감
실제로 실습하는 것은 재미있다. 실습 여러 번 하면서 배우면 금방 배울 것 같다.
Counter 라이브러리는 매우매우 유용할 것 같아서 추가로 공부해서 마스터해야겠다! 파이썬에는 정말 유용한 라이브러리가 많다. 아는 만큼 활용할 수 있다. 자세한 내용은 찾아보면서 해도 되니까 어떤 기능들이 있는지를 파악해두면 좋을 것 같다.