File size: 2,003 Bytes
21bdc64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 넀이버 μžλ™μ™„μ„±μœΌλ‘œ μ‹œλ“œ μ€‘μ‹¬μ˜ μ‹€μ œ λ™μ‹œκ²€μƒ‰ 경둜 트리λ₯Ό λ§Œλ“œλŠ” λͺ¨λ“ˆ (비곡식 μ—”λ“œν¬μΈνŠΈ)
import requests

AC_URL = "https://ac.search.naver.com/nx/ac"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"


def suggest(query: str, limit: int = 8) -> list[str]:
    # ν•œ 쿼리의 μžλ™μ™„μ„± 후보 리슀트 λ°˜ν™˜ (μ‹œλ“œ μžμ‹ μ€ μ œμ™Έ)
    params = {
        "q": query, "st": "100", "frm": "nx", "r_format": "json",
        "r_enc": "UTF-8", "r_unicode": "0", "t_koreng": "1", "ans": "2",
    }
    res = requests.get(AC_URL, params=params, headers={"User-Agent": UA}, timeout=5)
    res.raise_for_status()
    items = res.json().get("items") or [[]]
    out = []
    for it in items[0]:
        if it and it[0] and it[0] != query:
            out.append(it[0])
    return out[:limit]


def build_autocomplete_path(seed: str, vol_lookup: dict, depth1: int = 5, depth2: int = 2) -> dict:
    # μ‹œλ“œ β†’ μžλ™μ™„μ„±(depth1) β†’ 각자의 μžλ™μ™„μ„±(depth2)둜 μ‹€μ œ λ™μ‹œκ²€μƒ‰ 경둜 생성
    # vol_lookup: ν‚€μ›Œλ“œ β†’ κ²€μƒ‰λŸ‰ (검색광고 데이터에 있으면 ν‘œμ‹œ, μ—†μœΌλ©΄ None)
    nodes = [{"id": 0, "keyword": seed, "volume": vol_lookup.get(seed), "depth": 0}]
    edges, seen, nid = [], {seed}, 1

    for s1 in suggest(seed, depth1):
        if s1 in seen:
            continue
        seen.add(s1)
        n1 = nid; nid += 1
        nodes.append({"id": n1, "keyword": s1, "volume": vol_lookup.get(s1), "depth": 1})
        edges.append({"source": 0, "target": n1, "edge_type": "autocomplete"})

        for s2 in suggest(s1, depth2):
            if s2 in seen:
                continue
            seen.add(s2)
            n2 = nid; nid += 1
            nodes.append({"id": n2, "keyword": s2, "volume": vol_lookup.get(s2), "depth": 2})
            edges.append({"source": n1, "target": n2, "edge_type": "autocomplete"})

    return {"nodes": nodes, "edges": edges}