File size: 14,162 Bytes
08fb91a
47e7138
08fb91a
 
c64138a
cb92864
47e7138
 
 
 
08fb91a
cb92864
08fb91a
cb92864
 
 
47e7138
c64138a
 
 
cb92864
47e7138
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92864
 
47e7138
 
08fb91a
cb92864
 
08fb91a
 
c64138a
cb92864
47e7138
08fb91a
cb92864
c64138a
 
 
 
cb92864
 
c64138a
 
 
08fb91a
 
cb92864
 
c64138a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92864
 
c64138a
cb92864
 
08fb91a
cb92864
 
 
 
08fb91a
 
 
 
 
 
 
 
cb92864
 
08fb91a
 
 
cb92864
08fb91a
 
 
 
 
 
 
cb92864
 
 
08fb91a
 
 
 
 
 
 
 
 
 
cb92864
 
 
08fb91a
 
 
 
cb92864
08fb91a
 
cb92864
 
08fb91a
 
 
 
cb92864
08fb91a
 
 
 
 
cb92864
08fb91a
cb92864
08fb91a
 
 
 
 
 
 
cb92864
47e7138
cb92864
 
08fb91a
cb92864
 
 
 
c64138a
 
 
47e7138
c64138a
 
08fb91a
47e7138
08fb91a
cb92864
c64138a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47e7138
c64138a
 
 
 
 
 
 
 
 
 
08fb91a
47e7138
c64138a
cb92864
c64138a
 
cb92864
 
08fb91a
 
c64138a
08fb91a
c64138a
 
 
 
 
 
 
cb92864
 
 
 
47e7138
08fb91a
47e7138
 
 
08fb91a
cb92864
 
 
 
47e7138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92864
47e7138
 
cb92864
 
 
 
08fb91a
47e7138
 
08fb91a
cb92864
47e7138
 
 
 
 
 
 
 
cb92864
 
 
 
c64138a
 
 
 
 
08fb91a
47e7138
08fb91a
cb92864
 
 
6bf34b8
 
 
 
 
 
47e7138
 
 
 
6bf34b8
47e7138
 
6bf34b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb92864
6bf34b8
 
 
 
 
 
 
 
 
cb92864
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import re
import sys
import time
from collections import Counter
from datetime import datetime, timedelta

# μœˆλ„μš° μ½˜μ†” UnicodeEncodeError μ™„μ „ λ°©μ§€
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

# μˆ˜μ§‘ λŒ€μƒ μΉ΄ν…Œκ³ λ¦¬ sid - μ‚¬μš©μžμ˜ λ“€μ–Ό ν•˜μ΄λΈŒλ¦¬λ“œ ν•„ν„° 지침에 λ§žμΆ”μ–΄ κ²½μ œμ™€ IT/과학을 λͺ¨λ‘ μˆ˜μ§‘ν•©λ‹ˆλ‹€.
categories_sid = {
    "경제": "101",
    "IT/κ³Όν•™": "105",
}
NUM_ARTICLES_PER_DATE_CAT = 20  # μΉ΄ν…Œκ³ λ¦¬λ³„/λ‚ μ§œλ³„ μˆ˜μ§‘λŸ‰ (7일 * 2개 μΉ΄ν…Œκ³ λ¦¬ * 20 = μ΅œλŒ€ 280건 링크 νŒŒμ‹±)

# AI 및 금육/ν•€ν…Œν¬ ν‚€μ›Œλ“œ 리슀트 (ꡐ차 ν•˜μ΄λΈŒλ¦¬λ“œ 필터링 적용)
AI_KEYWORDS = [
    "AI", "인곡지λŠ₯", "μƒμ„±ν˜• AI", "λŒ€κ·œλͺ¨μ–Έμ–΄λͺ¨λΈ", "LLM", "GPT", 
    "μ œλ―Έλ‚˜μ΄", "Gemini", "ν΄λ‘œλ“œ", "Claude", "λ¨Έμ‹ λŸ¬λ‹", "λ”₯λŸ¬λ‹"
]

FIN_KEYWORDS = [
    "ν•€ν…Œν¬", "금육", "은행", "μΉ΄λ“œ", "증ꢌ", "페이", "μ†‘κΈˆ", "결제", 
    "μžμ‚°κ΄€λ¦¬", "μ‹ μš©ν‰κ°€", "μ‹ μš©", "투자", "λ§ˆμ΄λ°μ΄ν„°", "λ‘œλ³΄μ–΄λ“œλ°”μ΄μ €", 
    "인터넷은행", "μΈμŠˆμ–΄ν…Œν¬", "μžμ‚°μš΄μš©", "μΉ΄μΉ΄μ˜€λ±…ν¬", "ν† μŠ€λ±…ν¬", 
    "케이뱅크", "λ„€μ΄λ²„νŽ˜μ΄", "카카였페이", "ν† μŠ€", "주식", "λ±…ν‚Ή", 
    "λ””μ§€ν„Έ 금육", "ST", "ν† ν°μ¦κΆŒ", "FDS", "금육 사기", "μ΄μƒκ±°λž˜"
]

FINTECH_AI_KEYWORDS = AI_KEYWORDS + FIN_KEYWORDS  # μ‹œκ°ν™” ν˜Έν™˜μš© 전체 λͺ©λ‘

print("[INIT] ChromeDriver μ΄ˆκΈ°ν™” 쀑...")
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--headless")  # 속도 및 μ•ˆμ •μ„± κ·ΉλŒ€ν™”λ₯Ό μœ„ν•΄ headless λͺ¨λ“œ ν™œμ„±ν™”
driver = webdriver.Chrome(service=service, options=options)
print("[INIT] [OK] λΈŒλΌμš°μ € μ‹€ν–‰ μ™„λ£Œ")


def get_article_links(driver, sid: str, target_date: str, num_articles: int) -> list[str]:
    article_links: list[str] = []
    # 20κ°œμ”© λŠμ–΄μ„œ νŽ˜μ΄μ§€λ³„ 직접 λ‘œλ“œν•˜μ—¬ 속도λ₯Ό 10λ°° 이상 ν–₯μƒμ‹œν‚΅λ‹ˆλ‹€
    max_pages = (num_articles // 20) + 1

    selectors = [
        ".list_body a",
        "ul.type06_headline a",
        "ul.type06 a",
        "a.sa_text_title",
        ".sa_text a",
    ]

    for page in range(1, max_pages + 1):
        page_url = f"https://news.naver.com/main/list.naver?mode=LSD&mid=sec&sid1={sid}&date={target_date}&page={page}"
        print(f"  [LINK] νŽ˜μ΄μ§€ 이동 (Page {page}): {page_url}")
        try:
            driver.get(page_url)
            time.sleep(1.5)
        except Exception as e:
            print(f"    [LINK] ⚠️ νŽ˜μ΄μ§€ λ‘œλ“œ 였λ₯˜ (μŠ€ν‚΅): {e}")
            continue

        found_in_page = 0
        for selector in selectors:
            elements = driver.find_elements(By.CSS_SELECTOR, selector)
            for element in elements:
                try:
                    url = element.get_attribute("href")
                    if (
                        url
                        and "news.naver.com" in url
                        and "/article/" in url
                        and "/comment/" not in url
                        and url not in article_links
                    ):
                        article_links.append(url)
                        found_in_page += 1
                        if len(article_links) >= num_articles:
                            break
                except Exception:
                    continue
            if len(article_links) >= num_articles:
                break

        print(f"    -> Page {page}μ—μ„œ {found_in_page}개 기사 링크 확보 (λˆ„μ : {len(article_links)}개)")
        if len(article_links) >= num_articles or found_in_page == 0:
            break

    print(f"  [LINK] βœ… {target_date} 일자 총 {len(article_links)}개 링크 확보\n")
    return article_links[:num_articles]


def parse_article_detail(driver, article_url, category):
    driver.get(article_url)
    time.sleep(1.5)
    article_data = {
        "article_id": "",
        "title": "",
        "content": "",
        "url": article_url,
        "published_date": "",
        "source": "",
        "author": "",
        "category": category,
    }
    try:
        match = re.search(r"article/(\d+)/(\d+)", article_url)
        article_data["article_id"] = (
            f"ART_{match.group(1)}_{match.group(2)}" if match else f"ART_{datetime.now().strftime('%Y%m%d%H%M%S')}"
        )
        for sel in [
            "#title_area span",
            "#ct .media_end_head_headline",
            ".media_end_head_headline",
            "h2#title_area",
            ".news_end_title",
        ]:
            try:
                el = driver.find_element(By.CSS_SELECTOR, sel)
                if el.text.strip():
                    article_data["title"] = el.text.strip()
                    break
            except:
                continue
        for sel in [
            "#dic_area",
            "article#dic_area",
            ".go_trans._article_content",
            "._article_body_contents",
        ]:
            try:
                el = driver.find_element(By.CSS_SELECTOR, sel)
                if el.text.strip():
                    article_data["content"] = el.text.strip()
                    break
            except:
                continue
        try:
            el = driver.find_element(By.CSS_SELECTOR, "a.media_end_head_top_logo img")
            article_data["source"] = el.get_attribute("alt")
        except:
            try:
                el = driver.find_element(By.CSS_SELECTOR, ".media_end_head_top_logo_text")
                article_data["source"] = el.text.strip()
            except:
                pass
        try:
            el = driver.find_element(
                By.CSS_SELECTOR,
                "span.media_end_head_info_datestamp_time, span[data-date-time]",
            )
            article_data["published_date"] = (el.get_attribute("data-date-time") or el.text).strip()
        except:
            article_data["published_date"] = datetime.now().strftime("%Y-%m-%d %H:%M")
        try:
            el = driver.find_element(
                By.CSS_SELECTOR,
                "em.media_end_head_journalist_name, span.byline_s",
            )
            article_data["author"] = el.text.strip()
        except:
            pass
    except Exception as e:
        print(f"    [PARSE] [WARN] νŒŒμ‹± 였λ₯˜: {e}")
    return article_data


# ── 1단계: 전체 기사 μˆ˜μ§‘ ──
all_articles = []
category_stats = {}

# μ˜€λŠ˜λΆ€ν„° 7일 μ „κΉŒμ§€μ˜ λ‚ μ§œ 리슀트 생성
target_dates = [(datetime.now() - timedelta(days=i)).strftime("%Y%m%d") for i in range(7)]

print(f"[CRAWL] [DATE] λŒ€μƒ μˆ˜μ§‘ λ‚ μ§œ (7일): {target_dates}")

for target_date in target_dates:
    print(f"\n{'=' * 60}")
    print(f"[CRAWL] [DATE] {target_date} 일자 μˆ˜μ§‘ μ‹œμž‘")
    print(f"{'=' * 60}")

    for category_name, sid in categories_sid.items():
        print(f"\n  [CRAWL] [{category_name} - {target_date}] μΉ΄ν…Œκ³ λ¦¬ μˆ˜μ§‘ μ‹œμž‘")
        
        # λ‚ μ§œλ³„/μΉ΄ν…Œκ³ λ¦¬λ³„ λͺ©ν‘œ μˆ˜μ§‘λŸ‰
        article_links = get_article_links(driver, sid, target_date, NUM_ARTICLES_PER_DATE_CAT)

        cat_key = f"{category_name}_{target_date}"
        cat_ok, cat_fail = 0, 0
        
        for idx, article_url in enumerate(article_links, 1):
            print(f"    [PARSE] ({idx}/{len(article_links)}) {article_url[:70]}...")
            article_data = parse_article_detail(driver, article_url, category_name)

            if article_data["title"] and article_data["content"]:
                # λ§Œμ•½ νŒŒμ‹±λœ published_dateκ°€ λΉ„μ—ˆκ±°λ‚˜ μ΄μƒν•˜λ‹€λ©΄ target_date 기반으둜 λ‚ μ§œ ν˜•μ‹ μ„€μ •
                if not article_data["published_date"] or "202" not in article_data["published_date"]:
                    formatted_date = f"{target_date[:4]}-{target_date[4:6]}-{target_date[6:]} 09:00"
                    article_data["published_date"] = formatted_date
                
                all_articles.append(article_data)
                cat_ok += 1
                print(f"      [OK] {article_data['title'][:40]}...")
                print(f"         언둠사: {article_data['source']} | λ‚ μ§œ: {article_data['published_date']}")
            else:
                cat_fail += 1
                missing = [
                    x
                    for x, v in [
                        ("제λͺ©", article_data["title"]),
                        ("λ³Έλ¬Έ", article_data["content"]),
                    ]
                    if not v
                ]
                print(f"      [FAIL] νŒŒμ‹±μ‹€νŒ¨ ({', '.join(missing)} μ—†μŒ)")
            time.sleep(0.5)

        category_stats[cat_key] = {"ok": cat_ok, "fail": cat_fail}
        print(f"\n    [CRAWL] [{category_name} - {target_date}] μ™„λ£Œ: 성곡 {cat_ok}개 / μ‹€νŒ¨ {cat_fail}개")

driver.quit()
print("\n[DONE] λΈŒλΌμš°μ € μ’…λ£Œ")
print(f"\n{'=' * 60}")
print("[SUMMARY] μˆ˜μ§‘ κ²°κ³Ό Summary")
print(f"{'=' * 60}")
total_ok = 0
total_fail = 0
for cat_key, s in category_stats.items():
    print(f"  {cat_key}: 성곡 {s['ok']}건 / μ‹€νŒ¨ {s['fail']}건")
    total_ok += s['ok']
    total_fail += s['fail']
print(f"  전체 μˆ˜μ§‘: 성곡 {total_ok}건 / μ‹€νŒ¨ {total_fail}건")

df_all = pd.DataFrame(all_articles)


# ── 2단계: 금육 AI λ“€μ–Ό ν•˜μ΄λΈŒλ¦¬λ“œ 필터링 (경제 -> AI / IT -> 금육) ──
print(f"\n{'=' * 60}")
print("[FILTER] 금육 AI λ“€μ–Ό ν•˜μ΄λΈŒλ¦¬λ“œ 필터링 μ‹œμž‘")
print("[FILTER] - 경제 μ„Ήμ…˜ 기사: AI ν‚€μ›Œλ“œ 쑴재 μ‹œ 톡과")
print("[FILTER] - IT/κ³Όν•™ μ„Ήμ…˜ 기사: 금육 ν‚€μ›Œλ“œ 쑴재 μ‹œ 톡과")
print(f"{'=' * 60}")

filtered_articles = []
for _, row in df_all.iterrows():
    text = f"{row['title']} {row['content']}"
    text_clean = text.lower().replace(" ", "")
    
    # 1. AI 도메인 λ§€μΉ­
    matched_ai = [kw for kw in AI_KEYWORDS if kw.lower().replace(" ", "") in text_clean]
    # 2. 금육/ν•€ν…Œν¬ 도메인 λ§€μΉ­
    matched_fin = [kw for kw in FIN_KEYWORDS if kw.lower().replace(" ", "") in text_clean]
    
    is_passed = False
    matched_info = []
    
    if row['category'] == "경제":
        if matched_ai:
            is_passed = True
            matched_info = matched_ai
    elif row['category'] == "IT/κ³Όν•™":
        if matched_fin:
            is_passed = True
            matched_info = matched_fin
            
    if is_passed:
        row_dict = row.to_dict()
        # μ‹œκ°ν™” 및 λ‘œκΉ…μ„ μœ„ν•΄ κ²°ν•©λœ λ§€μΉ­ ν‚€μ›Œλ“œ 정보 기둝
        row_dict["matched_keywords"] = ", ".join(matched_info)
        filtered_articles.append(row_dict)

df_filtered = pd.DataFrame(filtered_articles)

print(f"  전체 μˆ˜μ§‘: {len(df_all)}건")
print(f"  AI ν•€ν…Œν¬ ꡐ차 필터링 톡과: {len(df_filtered)}건 ({len(df_filtered) / max(len(df_all), 1) * 100:.1f}%)")
print("\n  [도메인별 λ§€μΉ­ μš”μ•½]")
all_kw = [kw for row in filtered_articles for kw in row["matched_keywords"].split(", ")]
kw_counts = Counter(all_kw)
print("    --- AI 기술 ν‚€μ›Œλ“œ λ§€μΉ­ ---")
for kw in AI_KEYWORDS:
    if kw_counts.get(kw, 0) > 0:
        print(f"      {kw}: {kw_counts.get(kw, 0)}건")
print("    --- 금육/ν•€ν…Œν¬ ν‚€μ›Œλ“œ λ§€μΉ­ ---")
for kw in FIN_KEYWORDS:
    if kw_counts.get(kw, 0) > 0:
        print(f"      {kw}: {kw_counts.get(kw, 0)}건")

df_filtered

# ── 3단계: μ €μž₯ ──
import os

output_dir = os.path.join("src", "graphBuilder", "scrapping")
os.makedirs(output_dir, exist_ok=True)
output_filename = os.path.join(output_dir, f"Articles_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx")
df_filtered.to_excel(output_filename, index=False, engine="openpyxl")
print(f"[SAVE] [OK] μ €μž₯ μ™„λ£Œ: {output_filename}")
print(f"[SAVE]    - AI ν•€ν…Œν¬ 기사: {len(df_filtered)}건")


# ── 4단계: ν‚€μ›Œλ“œ λΉˆλ„ μ‹œκ°ν™” ──
try:
    import platform
    from collections import Counter

    import matplotlib.pyplot as plt

    # 폰트 깨짐 λ°©μ§€ (Windows: Malgun Gothic, Mac: AppleGothic, Linux: NanumGothic)
    if platform.system() == "Windows":
        plt.rc("font", family="Malgun Gothic")
    elif platform.system() == "Darwin":
        plt.rc("font", family="AppleGothic")
    else:
        plt.rc("font", family="NanumGothic")
    plt.rcParams["axes.unicode_minus"] = False

    if not filtered_articles:
        print("μ‹œκ°ν™”ν•  데이터가 μ—†μŠ΅λ‹ˆλ‹€.")
    else:
        # λΉˆλ„μˆ˜ 계산
        all_kw = [kw for row in filtered_articles for kw in row["matched_keywords"].split(", ")]
        kw_counts = Counter(all_kw)

        # πŸ“Œ λ³€κ²½ 포인트: FINTECH_AI_KEYWORDS 전체 λͺ©λ‘μ„ μˆœμ„œλŒ€λ‘œ κ·Έλž˜ν”„μ— κ°•μ œ ν‘œμ‹œ (0건 포함)
        keywords = FINTECH_AI_KEYWORDS
        counts = [kw_counts.get(kw, 0) for kw in keywords]

        plt.figure(figsize=(12, 6))

        # λ§‰λŒ€ κ·Έλž˜ν”„ 생성
        bars = plt.bar(keywords, counts, color="skyblue", edgecolor="white")

        # λ§‰λŒ€ μœ„μ— 숫자(λΉˆλ„μˆ˜) ν‘œμ‹œ
        for bar in bars:
            height = bar.get_height()
            # λ§‰λŒ€μ˜ 쀑앙(x), λ§‰λŒ€μ˜ 높이(y) μœ„μΉ˜μ— ν…μŠ€νŠΈλ₯Ό 배치
            plt.text(
                bar.get_x() + bar.get_width() / 2.0,
                height,
                f"{height}",
                ha="center",
                va="bottom",
                size=11,
                fontweight="bold",
                color="black",
            )

        plt.title("μˆ˜μ§‘λœ AI ν•€ν…Œν¬ 기사 ν‚€μ›Œλ“œ μΆœν˜„ λΉˆλ„ (전체)", fontsize=15, pad=15)
        plt.xlabel("ν‚€μ›Œλ“œ", fontsize=12)
        plt.ylabel("μΆœν˜„ 횟수 (건)", fontsize=12)
        plt.grid(axis="y", linestyle="--", alpha=0.7)
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.show()
except ImportError:
    print("[INFO] matplotlib λΌμ΄λΈŒλŸ¬λ¦¬κ°€ μ„€μΉ˜λ˜μ–΄ μžˆμ§€ μ•Šμ•„ μ‹œκ°ν™” 단계λ₯Ό κ±΄λ„ˆλœλ‹ˆλ‹€.")