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 λΌμ΄λΈλ¬λ¦¬κ° μ€μΉλμ΄ μμ§ μμ μκ°ν λ¨κ³λ₯Ό 건λλλλ€.")
|