데브코스 TIL/Web Scrapping

Web Scraping 기초 4 시각화로 결과 요약하기 -Seaborn/Wordcloud -

예니ㅣ 2023. 10. 27. 15:05

강의

"시각화"는 정보를 요약해서 한눈에 보여주는 것입니다.

 

"Seaborn" 라이브러리는 matplotlib을 기반으로 하는 라이브러리 입니다.

다양한 그래프를 고수준(high-level)에서 쉽게 그릴 수 있습니다.

%pip install seaborn

# 시각화에 필요한 라이브러리를 불러와봅시다.
import seaborn as sns

# Scatterplot을 직접 그려봅시다
# 값 x=[1, 3, 2, 4]
# 값 y=[0.7,0.2,0.1,0.05]
sns.lineplot(x=[1, 3, 2, 4], y=[4, 3, 2, 1])

# Barplot을 직접 그려봅시다
# 범주 x=[1,2,3,4]
# 값 y=[0.7,0.2,0.1,0.05]
sns.barplot(x=[1,2,3,4],y=[0.7,0.2,0.1,0.05])

# matplotlib.pyplot을 불러와봅시다.
import matplotlib.pyplot as plt

# 제목을 추가해봅시다.
plt.title("Bar Plot")

# xlabel과 ylabel을 추가해봅시다.
plt.xlabel("X Label")
plt.ylabel("Y Label")

# lineplot에서 ylim을 2~3으로 제한해봅시다.
plt.ylim(2, 3)

# 크기를 (20, 10)으로 지정해봅시다.
plt.figure(figsize=(20, 10))

 

기상청 날씨 정보 조회

https://www.weather.go.kr/w/weather/forecast/short-term.do

# 스크래핑에 필요한 라이브러리를 불러와봅시다.
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를 이용해 기상청 날씨 데이터를 가져와봅시다.
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.weather.go.kr/w/weather/forecast/short-term.do")
driver.implicitly_wait(1)
temps = driver.find_element(By.ID, "my-tchart").text
temps = [int(i) for i in temps.replace("℃", "").split("\n")]
print(temps)

# 받아온 데이터를 통해 꺾은선 그래프를 그려봅시다.
# x = Elapsed Time(0~len(temperatures)
# y = temperatures
import seaborn as sns
import matplotlib.pyplot as plt

sns.lineplot(
    x = [i for i in range(len(temps))],
    y = temps
)

plt.ylim(min(temps)-2, max(temps)+2)
plt.title("Expected Temperature from now on")

plt.show()

 

해시코드 질문태그 빈도 시각화

https://hashcode.co.kr

# 다음 User-Agent를 추가해봅시다.
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"}

# 필요한 라이브러리를 불러온 후, 요청을 진행해봅시다.
# 응답을 바탕으로 BeautifulSoup 객체를 생성해봅시다.
import requests
from bs4 import BeautifulSoup

res = requests.get("https://hashcode.co.kr")
soup = BeautifulSoup(res.text, "html.parser")

# 필요한 라이브러리를 불러온 후, 요청을 진행해봅시다.
# 응답을 바탕으로 BeautifulSoup 객체를 생성해봅시다.
import requests
from bs4 import BeautifulSoup
import time

frequency = {}

for i in range(1, 11):
    res = requests.get("https://hashcode.co.kr/?page={}".format(i), user_agent)
    soup = BeautifulSoup(res.text, "html.parser")
    
# 질문의 빈도를 체크하는 dict를 만든 후, 빈도를 체크해봅시다.
    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)
    
frequency

# Counter를 사용해 가장 빈도가 높은 value들을 추출합니다.
from collections import Counter

counter = Counter(frequency)

counter.most_common(10)

# Seaborn을 이용해 이를 Barplot으로 그립니다.
import seaborn as sns
import matplotlib.pyplot as plt

x = [elem[0] for elem in counter.most_common(10)]
y = [elem[1] for elem in counter.most_common(10)]

# figure, xlabel, ylabel, title을 적절하게 설정해서 시각화를 완성해봅시다.
plt.figure(figsize=(20, 10))

sns.barplot(x=x, y=y)

plt.title("Frequency of question in Hashcode")
plt.xlabel("Tag")
plt.ylabel("Frequency")

plt.show()

코드 실행 결과

 

 


"Wordcloud" 라이브러리는 텍스트 클라우드를 그릴 수 있도록 하는 라이브러리 입니다.

"Konlpy"는 한국어에 대해 형태소를 분석하는 라이브러리 입니다.

%pip install wordcloud
%pip install konlpy

# 텍스트 구름을 그리기 위해 필요한 라이브러리를 불러와봅시다.
import matplotlib.pyplot as plt		# 시각화
from wordcloud import WordCloud		# 시각화
from collections import Counter		# 빈도 측정
from konlpy.tag import Hannanum		# 형태소 분석

# 워드클라우드를 만드는 데 사용할 애국가 가사입니다.
national_anthem = """
    동해물과 백두산이 마르고 닳도록
    하느님이 보우하사 우리나라 만세
    무궁화 삼천리 화려 강산
    대한 사람 대한으로 길이 보전하세
    남산 위에 저 소나무 철갑을 두른 듯
    바람 서리 불변함은 우리 기상일세
    무궁화 삼천리 화려 강산
    대한 사람 대한으로 길이 보전하세
    가을 하늘 공활한데 높고 구름 없이
    밝은 달은 우리 가슴 일편단심일세
    무궁화 삼천리 화려 강산
    대한 사람 대한으로 길이 보전하세
    이 기상과 이 맘으로 충성을 다하여
    괴로우나 즐거우나 나라 사랑하세
    무궁화 삼천리 화려 강산
    대한 사람 대한으로 길이 보전하세
    """
    
# Hannanum 객체를 생성한 후, .nouns()를 통해 명사를 추출합니다.
hannanum = Hannanum()
nouns = hannanum.nouns(national_anthem)
words = [noun for noun in nouns if len(noun) > 1]
words[:10]

# counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(words)
counter

# WordCloud를 이용해 텍스트 구름을 만들어봅시다.
wordcloud = WordCloud(
    fonts_path = "폰트 경로",
    background_color = "white",
    width = 1000,
    height = 1000
)

img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)

 

해시코드 질문 키워드

https://hashcode.co.kr

# 다음 User-Agent를 추가해봅시다.
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"}

# Pagination이 되어있는 질문 리스트의 제목을 모두 가져와 리스트 questions에 저장해봅시다.
# https://hashcode.co.kr/?page={i}
# 과도한 요청을 방지하기 위해 0.5초마다 요청을 보내봅시다.
import requests
from bs4 import BeautifulSoup
import time

questions = []

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)
    
questions[:10]

# 텍스트 구름을 그리기 위해 필요한 라이브러리를 불러와봅시다.
import matplotlib.pyplot as plt		# 시각화
from wordcloud import WordCloud		# 시각화
from collections import Counter		# 빈도 측정
from konlpy.tag import Hannanum		# 형태소 분석

# Hannanum 객체를 생성한 후, .nouns()를 통해 명사를 추출합니다.
hannanum = Hannanum()

words = []

for question in questions:
    nouns = hannanu.nouns(question)
    words += nouns
    
words

# counter를 이용해 각 단어의 개수를 세줍니다.
counter = Counter(words)
counter

# WordCloud를 이용해 텍스트 구름을 만들어봅시다.
wordcloud = WordCloud(
    font_path = "폰트 경로",
    background_color = "white",
    height = 1000
    width = 1000
)

img = wordcloud.generate_from_frequencies(counter)
plt.imshow(img)