프로그래밍/Python

Python을 이용해 네이버 뉴스 크롤링 및 CSV저장 해보기

dinggul94 2024. 10. 20. 00:14
728x90

필수 라이브러리 설치

pip install beautifulsoup4 requests pandas

 

크롤링 후 CSV 저장(한글이나 일본어의 경우 UTF8로 인코딩해서 내보내야 안깨짐)

import requests
from bs4 import BeautifulSoup
import pandas as pd

# 크롤링할 키워드 설정
query = "Python"
url = f"https://search.naver.com/search.naver?where=news&query={query}"

# 웹 페이지 요청
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)

# BeautifulSoup으로 HTML 파싱
soup = BeautifulSoup(response.text, "html.parser")

# 뉴스 기사 추출 (제목과 링크)
articles = []
for item in soup.select("a.news_tit"):
    title = item.get_text()
    link = item['href']
    articles.append({'title': title, 'link': link})

# pandas로 DataFrame 생성
df = pd.DataFrame(articles)

# DataFrame을 CSV 파일로 저장
df.to_csv("naver_news.csv", index=False, encoding='utf-8-sig')

print("CSV 파일로 저장 완료!")

 

728x90