-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnaver_news_crawler.py
More file actions
328 lines (271 loc) · 11.6 KB
/
naver_news_crawler.py
File metadata and controls
328 lines (271 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import os
import re
import uuid
import time
import random
from datetime import datetime, timedelta, timezone
# 한국 시간대 설정
KST = timezone(timedelta(hours=9))
def now_kst():
"""한국 시간으로 현재 시간 반환"""
return datetime.now(KST)
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from pymongo import MongoClient
def save_to_mongodb(documents, db_name="crame", collection_name="news"):
"""
MongoDB에 뉴스 문서를 저장하는 함수
- URL 기준 중복 체크
- 중복 시 키워드 배열 업데이트
- TTL 인덱스로 24시간 후 자동 삭제
"""
# Docker 환경의 MongoDB 연결
client = MongoClient("mongodb://root:1234@mongodb:27017",
authSource="admin")
# 데이터베이스와 컬렉션 선택
db = client[db_name]
collection = db[collection_name]
# 24시간 * 3 = 3일 후 자동 삭제되는 TTL 인덱스 설정
collection.create_index("date", expireAfterSeconds=86400 * 3)
# URL 기준 중복 체크를 위한 유니크 인덱스
collection.create_index("url", unique=True)
# 문서 저장 로직
if documents:
saved_count = 0
duplicate_count = 0
for doc in documents:
try:
# URL로 기존 문서 검색
existing_doc = collection.find_one({"url": doc["url"]})
if existing_doc:
# 기존 문서가 있으면 키워드 배열에 추가
if "keywords" not in existing_doc:
existing_doc["keywords"] = []
if doc["keyword"] not in existing_doc["keywords"]:
collection.update_one(
{"url": doc["url"]}, {"$push": {"keywords": doc["keyword"]}}
)
duplicate_count += 1
else:
# 새 문서면 keywords 배열로 저장
doc["keywords"] = [doc["keyword"]]
del doc["keyword"] # 단일 keyword 필드 제거
collection.insert_one(doc)
saved_count += 1
except Exception as e:
print(f"❗ 저장 중 오류 발생: {e}")
continue
print(f"✅ {saved_count}개 새로운 문서를 MongoDB에 저장했습니다.")
if duplicate_count > 0:
print(f"⚠️ {duplicate_count}개 중복 문서의 키워드가 업데이트되었습니다.")
else:
print("저장할 데이터가 없습니다.")
def setup_driver():
"""
Selenium WebDriver 설정 함수
- 헤드리스 모드
- 자동화 감지 방지
- Docker 환경에 맞는 설정
"""
options = Options()
options.add_argument("--headless=new")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1920,1080")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--disable-gpu")
# 원격 셀레니움 컨테이너에 요청
driver = webdriver.Remote(
command_executor="http://selenium:4444/wd/hub",
options=options
)
# 원격 셀레니움 컨테이너에 요청
driver = webdriver.Remote(
command_executor="http://selenium:4444/wd/hub",
options=options
)
return driver
def normalize_time(text):
"""
상대적 시간 표현을 datetime 객체로 변환
- '분 전', '시간 전', '일 전', '주 전' 등의 표현 처리
- 'YYYY.MM.DD.' 형식의 날짜 처리
"""
now = now_kst() # 한국 시간
if "분 전" in text:
minutes = int(re.search(r"\d+", text).group())
return now - timedelta(minutes=minutes)
elif "시간 전" in text:
hours = int(re.search(r"\d+", text).group())
return now - timedelta(hours=hours)
elif "일 전" in text:
days = int(re.search(r"\d+", text).group())
return now - timedelta(days=days)
elif "주 전" in text:
weeks = int(re.search(r"\d+", text).group())
return now - timedelta(weeks=weeks)
elif re.match(r"\d{4}\.\d{2}\.\d{2}\.", text):
# 날짜만 있는 경우 현재 시간을 사용
date_str = text.strip()
base_time = datetime.strptime(date_str, "%Y.%m.%d.")
current_time = now_kst()
return datetime.combine(base_time.date(), current_time.time())
return None
def scroll_until_done(driver, max_scrolls=50):
"""
페이지 끝까지 스크롤하며 모든 뉴스 기사 로드
- 최대 50회 스크롤
- 기사 수가 증가하지 않으면 종료
"""
last_article_count = 0
for i in range(max_scrolls):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(random.uniform(1.5, 2.5))
# 뉴스 아이템 선택자 수정
articles = driver.find_elements(
By.CSS_SELECTOR,
"div.sds-comps-vertical-layout.sds-comps-full-layout.fds-news-item-list-tab > div",
)
article_count = len(articles)
print(f"스크롤 {i+1}회 후 기사 수: {article_count}")
if article_count <= last_article_count:
print(f"✅ 스크롤 종료: 총 {article_count}개 기사 탐색됨")
break
last_article_count = article_count
def crawl_naver_news(keyword, start_date, end_date):
"""
네이버 뉴스 크롤링 메인 함수
- 키워드 검색
- 기사 정보 추출 (제목, 요약, 언론사, 시간, 이미지 등)
- 1시간 단위로 필터링
"""
url = (
f"https://search.naver.com/search.naver?where=news&query={keyword}"
f"&sm=tab_opt&sort=1&photo=0&field=0&pd=7&ds={start_date}&de={end_date}"
f"&nso=so%3Ar%2Cp%3A1h" # 1시간 단위 검색
)
driver = setup_driver()
documents = []
try:
driver.get(url)
time.sleep(2)
scroll_until_done(driver)
# 뉴스 아이템 선택
articles = driver.find_elements(
By.CSS_SELECTOR,
"div.sds-comps-vertical-layout.sds-comps-full-layout.fds-news-item-list-tab > div",
)
print(f"\n🔍 '{keyword}' 키워드로 {len(articles)}개의 뉴스 기사를 찾았습니다.")
for idx, article in enumerate(articles, 1):
try:
print(f"\n처리 중인 기사 {idx}/{len(articles)}")
# 제목 추출
title_elem = article.find_element(
By.CSS_SELECTOR, "span.sds-comps-text-type-headline1"
)
title = title_elem.text.strip()
# 링크 추출 - sds-comps-base-layout sds-comps-full-layout의 자식의 sds-comps-vertical-layout sds-comps-full-layout의 자식 a태그
link = article.find_element(
By.CSS_SELECTOR,
"div.sds-comps-base-layout.sds-comps-full-layout > div.sds-comps-vertical-layout.sds-comps-full-layout > a",
).get_attribute("href")
if not link or not title:
print(f"❗ 기사 {idx}: URL 또는 제목 누락")
continue
# 요약 추출
try:
summary = article.find_element(
By.CSS_SELECTOR, "span.sds-comps-text-type-body1"
).text.strip()
except:
summary = ""
print(f"❗ 기사 {idx}: 요약 누락")
# 언론사와 시간 추출
text_elements = article.find_elements(
By.CSS_SELECTOR, "span.sds-comps-text-type-body2"
)
publisher = ""
pub_time = None
for elem in text_elements:
text = elem.text.strip()
if "전" in text or text.count(".") >= 2: # 시간 정보
pub_time = normalize_time(text)
else: # 언론사 정보
publisher = text
if not publisher or not pub_time:
print(f"❗ 기사 {idx}: 언론사 또는 시간 정보 누락")
# 미리보기 이미지 URL 추출
try:
img_elem = article.find_element(
By.CSS_SELECTOR, "div.sds-rego-thumb-overlay img"
)
img_url = img_elem.get_attribute("src")
except:
img_url = ""
print(f"❗ 기사 {idx}: 이미지 URL 누락")
# 문서 생성
doc = {
"news_uuid": str(uuid.uuid4()),
"title": title,
"summary": summary,
"publisher": publisher,
"url": link,
"date": pub_time.strftime("%Y-%m-%dT%H:%M") if pub_time else None,
"img_url": img_url,
"keyword": keyword,
}
print(f"✅ 기사 {idx} 처리 완료:")
print(f" - 제목: {title[:30]}...")
print(f" - URL: {link}")
documents.append(doc)
except Exception as e:
print(f"❗ 기사 {idx} 파싱 오류:", str(e))
continue
except Exception as e:
print("❗ 크롤링 전체 오류:", e)
finally:
driver.quit()
print(f"\n총 {len(documents)}/{len(articles)}개 기사 처리 완료")
return documents
if __name__ == "__main__":
# 크롤링할 키워드 리스트
keywords = ["비트코인", "리플", "이더리움"]
# 오늘 날짜 기준으로 검색
now = now_kst()
end_date = now.strftime("%Y.%m.%d")
start_date = now.strftime("%Y.%m.%d")
# 각 키워드별 크롤링 실행
total_new_articles = 0 # 새로운 기사 수
total_duplicate_articles = 0 # 중복 기사 수
total_keywords_updated = 0 # 업데이트된 키워드 수
for keyword in keywords:
print(f"\n🔍 키워드 '{keyword}' 크롤링 시작...")
result = crawl_naver_news(keyword, start_date, end_date)
print(f"📌 '{keyword}' 키워드로 수집된 뉴스 기사 수: {len(result)}")
if result:
# MongoDB 저장 결과 확인
client = MongoClient("mongodb://root:1234@mongodb:27017",
authSource="admin")
client = MongoClient("mongodb://root:1234@mongodb:27017",
authSource="admin")
db = client["crame"]
collection = db["news"]
# 저장 전 기존 문서 수 확인
before_count = collection.count_documents({})
# 문서 저장
save_to_mongodb(result)
# 저장 후 기존 문서 수 확인
after_count = collection.count_documents({})
# 새로운 기사 수와 중복 기사 수 계산
new_articles = after_count - before_count
duplicate_articles = len(result) - new_articles
total_new_articles += new_articles
total_duplicate_articles += duplicate_articles
print(f"\n✅ 크롤링 결과 요약:")
print(f" - 총 {len(keywords)}개 키워드 처리")
print(f" - 새로운 기사: {total_new_articles}개")
print(f" - 중복 기사: {total_duplicate_articles}개")
print(f" - 총 처리된 기사: {total_new_articles + total_duplicate_articles}개")