크롤링 기초
크롤링은 웹사이트의 정보를 자동으로 수집하는 기술을 말한다.
쉽게 말하면, 사람이 웹사이트에 접속해서 뉴스 제목을 하나하나 읽는 대신, 프로그램(크롤러)이 자동으로 사이트에 접속하고, 필요한 정보를 찾아서 가져오는 것이다.
예를 들어, 다음과 같은 작업을 자동으로 할 수 있다.
- 네이버 뉴스에서 키워드 관련 기사 제목만 싹 모으기
- 쇼핑몰에서 특정 상품 가격을 정기적으로 확인하기
- 블로그에서 특정 키워드가 포함된 글을 수집하기
크롤링이라는 것을 알게된 후, 처음으로 해보고 싶었던 건 나의 전공과 연관지어 보는 것이었다.
컴퓨터공학과 아이들이 배우는 언어와 개발을 경영학과인 나의 전공과도 연관지어 응용해보고 싶었다.
그래서 해보고 싶었던 것은 다음과 같은 작업이다.
네이버 뉴스 -> 경제면 -> 금융관련 기사 크롤링 |
요즘의 금융트렌드 키워드 찾기 |
금융트렌드 키워드별 빈도수 그래프 도출 |
1. python 코드: 코드를 실행하면 네이버 뉴스에 자동으로 들어가지며, 관련 기사를 다 찾아서 알려준다.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from collections import Counter
import matplotlib.pyplot as plt
# ✅ 크롬 드라이버 경로
chrome_driver_path = "C:/Users/kwater/Desktop/chromedriver/chromedriver.exe"
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# ✅ 1. 네이버 경제 뉴스 메인 페이지 열기
driver.get("https://news.naver.com/section/101")
time.sleep(2)
# ✅ 2. 금융 탭 클릭
finance_tab = driver.find_element(By.LINK_TEXT, "금융")
finance_tab.click()
time.sleep(2)
# ✅ 3. 기사 더보기 계속 누르기
while True:
try:
more_button = driver.find_element(By.CLASS_NAME, "btn_more")
more_button.click()
time.sleep(2)
except:
print("✅ 더보기 버튼 없음. 기사 모두 불러옴!")
break
# ✅ 4. 기사 리스트 가져오기
articles = driver.find_elements(By.CSS_SELECTOR, "a.sa_text_title")
target_date = "2025.04.29." # 날짜 끝에 꼭 점(.) 포함!!
title_list = [] # 제목 저장할 리스트
print("\n===== 2025-04-29 금융 뉴스 =====\n")
# ✅ 5. 각 기사 링크 클릭해서 상세페이지 가서 날짜 체크
for article in articles:
try:
link = article.get_attribute("href")
# 새 창으로 열기
driver.execute_script("window.open(arguments[0]);", link)
driver.switch_to.window(driver.window_handles[-1])
time.sleep(1.5) # 로딩 대기
# 날짜 가져오기
date = driver.find_element(By.CSS_SELECTOR, "span.media_end_head_info_datestamp_time").text.strip()
if target_date in date:
title = driver.find_element(By.CSS_SELECTOR, "h2.media_end_head_headline").text.strip()
print(title)
title_list.append(title) # 리스트에 저장
# 현재 창 닫기 (안전 체크)
if len(driver.window_handles) > 1:
driver.close()
driver.switch_to.window(driver.window_handles[0])
except Exception as e:
print("에러 발생:", e)
# 에러가 나도 안전하게 창 관리
if len(driver.window_handles) > 1:
driver.close()
driver.switch_to.window(driver.window_handles[0])
continue
# ✅ 6. 수집한 제목 리스트로 키워드 분석!
# 모든 제목을 하나로 합치기
text = " ".join(title_list)
# 단어로 쪼개기
words = text.split()
# 너무 짧은 단어(1글자)는 제거
words = [word for word in words if len(word) > 1]
# 단어 빈도수 세기
counter = Counter(words)
# 가장 많이 등장한 단어 10개 뽑기
most_common_words = counter.most_common(10)
print("\n===== 2025-04-29 금융 뉴스 키워드 TOP 10 =====\n")
for word, count in most_common_words:
print(f"{word}: {count}회")
# ✅ 7. 그래프로 시각화
labels, counts = zip(*most_common_words)
plt.figure(figsize=(10,5))
plt.bar(labels, counts)
plt.title("2025-04-29 금융 뉴스 키워드 TOP 10")
plt.xlabel("단어")
plt.ylabel("횟수")
plt.show()
2. 코드 실행 결과: terminal 창에는 다음과 같이 뜨며, 이를 그래프로 도출해준다. (코드 상에 그래프 도출까지 포함되어 있다.)
'Python' 카테고리의 다른 글
Python: 연습 5 (데이터 분석과 시각화 1) (0) | 2025.04.30 |
---|---|
Python: 연습 4 (크롤링 심화) (0) | 2025.04.29 |
Python: 연습 2 (웹페이지 html 만들기) (0) | 2025.04.29 |
Python: 연습 1 (랜덤 운세 뽑기) (2) | 2025.04.29 |
Python: 설치 및 실행 (0) | 2025.04.29 |