""" 아웃바운드 리스트 병원의 공식 전화번호를 홈페이지에서 모은다. - 홈페이지 + 오시는 길·연락처 링크(최대 3개)를 JS 없이 받아 본문 텍스트에서 번호와 앞 라벨을 함께 뽑는다 - 분류: 대표(대표·TEL·전화·상담·예약·고객) / 홍보·마케팅(홍보·마케팅·광고·제휴·PR) / 기타 - 팩스와 개인정보처리방침 속 신고기관 번호(개인정보침해·대검·경찰 등)는 뺀다 - 번호를 만들어내지 않는다. 못 찾으면 '확인 필요' python3 docs/reports/outbound_webforai/crawl_phones.py <출력.json> """ import json import re import subprocess import sys import urllib.parse from concurrent.futures import ThreadPoolExecutor import openpyxl UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36" PHONE = re.compile(r"(?||", " ", h, flags=re.S | re.I) t = re.sub(r"<[^>]+>", " ", t) return re.sub(r"\s+", " ", t) def norm(p): d = re.sub(r"\D", "", p) if d.startswith("02"): return f"02-{d[2:-4]}-{d[-4:]}" if len(d) == 8: # 1588-0000 return f"{d[:4]}-{d[4:]}" return f"{d[:3]}-{d[3:-4]}-{d[-4:]}" def phones(text, url): out = [] for m in PHONE.finditer(text): ctx = text[max(0, m.start() - 30):m.start()] if EXCLUDE.search(ctx[-20:]): continue num = norm(m.group(1)) if len(re.sub(r"\D", "", num)) < 8: continue kind = "pr" if LABEL_PR.search(ctx[-15:]) else ("main" if LABEL_MAIN.search(ctx[-20:]) else "other") out.append({"num": num, "kind": kind, "ctx": ctx.strip()[-20:], "url": url}) return out def crawl(row): seq, name, home = row res = {"seq": seq, "name": name, "home": home, "found": [], "error": None} if not home: res["error"] = "홈페이지 없음" return res try: h = fetch(home) if len(h) < 500: res["error"] = "홈페이지 응답 없음" return res res["found"] += phones(text_of(h), home) links = [] for m in re.finditer(r']+href="([^"#]+)"[^>]*>(.*?)', h, re.S | re.I): href, label = m.group(1), re.sub(r"<[^>]+>", "", m.group(2)) if href.startswith(("javascript", "mailto", "tel")): continue if SUBPAGE.search(href) or SUBPAGE.search(label): u = urllib.parse.urljoin(home, href) if urllib.parse.urlparse(u).netloc == urllib.parse.urlparse(home).netloc and u not in links: links.append(u) for u in links[:3]: res["found"] += phones(text_of(fetch(u)), u) except Exception as e: # 한 곳 실패가 전체를 멈추지 않게 기록만 한다 res["error"] = repr(e)[:120] return res def summarize(res): cnt = {} for f in res["found"]: cnt.setdefault(f["num"], {"main": 0, "pr": 0, "other": 0, "ctx": f["ctx"], "url": f["url"]}) cnt[f["num"]][f["kind"]] += 1 main = sorted([n for n, c in cnt.items() if c["main"]], key=lambda n: -(cnt[n]["main"] * 10 + cnt[n]["other"])) pr = [n for n, c in cnt.items() if c["pr"]] other = sorted([n for n, c in cnt.items() if not c["main"] and not c["pr"]], key=lambda n: -cnt[n]["other"]) res["main"] = main[:1] or other[:1] res["main_basis"] = "라벨(대표·전화·상담 등)" if main else ("빈도" if other else "") res["extra"] = [n for n in main[1:] + other if n not in res["main"]][:3] res["pr"] = pr res["sources"] = sorted({cnt[n]["url"] for n in res["main"] + pr}) return res def main(xlsx, out): ws = openpyxl.load_workbook(xlsx, data_only=True)["Outbound"] col = {ws.cell(2, c).value: c for c in range(1, ws.max_column + 1)} rows = [(ws.cell(r, col["순번"]).value, ws.cell(r, col["병원명"]).value, ws.cell(r, col["공식 웹사이트"]).value) for r in range(3, ws.max_row + 1) if ws.cell(r, col["병원명"]).value] with ThreadPoolExecutor(10) as ex: results = [summarize(r) for r in ex.map(crawl, rows)] json.dump(results, open(out, "w"), ensure_ascii=False, indent=1) print(out, len(results)) if __name__ == "__main__": main(*sys.argv[1:3])