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
'프로그래밍 > Python' 카테고리의 다른 글
간단한 IDE 툴 만들기(Python) (5) | 2024.10.25 |
---|---|
Python을 이용하여 youtube 크롤링(Google Cloud API활용) (2) | 2024.10.20 |
파이썬 Selenium 사용해보기 (0) | 2024.10.19 |