import os import requests from bs4 import BeautifulSoup import openpyxl def crawl_and_update_excel(file_path, output_path="excel_output_result_v4.xlsx"): # 1. 엑셀 파일 로드 wb = openpyxl.load_workbook(file_path) ws = wb.active # 현재 활성화된 시트 선택 # 웹사이트 차단 방지를 위한 브라우저 헤더 설정 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } print("데이터 처리를 시작합니다...") # 2. 246행부터 시작해서 데이터가 있는 마지막 행까지 반복 for row in range(246, ws.max_row + 1): cell_L = ws.cell(row=row, column=12).value # L열 (12번째 열) cell_K = ws.cell(row=row, column=11).value # K열 (11번째 열) # 조건: L열이 '페이지'이고 K열에 URL 주소가 입력되어 있는 경우 if cell_L == "게시판" and cell_K: url = str(cell_K).strip() # URL 형식이 완전하지 않은 경우 http 프로토콜 자동 붙임 if not url.startswith("http"): url = "https://" + url print(f"[행 {row}] 크롤링 시도 중: {url}") try: # 3. URL 접속 및 HTML 가져오기 response = requests.get(url, headers=headers, timeout=10) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') # ---
내부 탐색 --- main_content = soup.find('main', class_='content') search_area = main_content if main_content else soup # 만약 해당 태그가 없으면 전체에서 찾음 license_type = None # 영역 안의 모든 태그의 링크(href) 검사 for a_tag in search_area.find_all('a', href=True): href = a_tag['href'] if 'www.kogl.or.kr/info/licenseType' in href: # licenseType 뒤에 오는 숫자 추출 (예: licenseType1 -> 1) try: start_idx = href.find('licenseType') + len('licenseType') num = href[start_idx] # 숫자 한자리 추출 if num.isdigit(): license_type = f"{num}유형" break except Exception: pass # ★ 조건 수정: 유형이 존재할 때만 O, P, Q열 모두 작성 if license_type: # O열 (15번째 열)에 결과 작성 ws.cell(row=row, column=15, value=license_type) print(f" -> O열 입력: {license_type}") # P열 (16번째 열)에 "게시판" 작성 ws.cell(row=row, column=16, value="게시판") print(f" -> P열 입력: 게시판") # class="content-license" 내부 하이퍼링크 존재 여부 체크 content_license_area = soup.find(class_='content-license') has_license_link = False if content_license_area: for a_tag in content_license_area.find_all('a', href=True): if 'www.kogl.or.kr/info/licenseType' in a_tag['href']: has_license_link = True break # Q열 (17번째 열)에 존재하면 Y 작성 if has_license_link: ws.cell(row=row, column=17, value="Y") print(f" -> Q열 입력: Y") # ★ 유형이 없을 때: O열에 "미부착"을 입력하고, P와 Q열은 건너뜀 else: ws.cell(row=row, column=15, value="미부착") print(f" -> [행 {row}] 공공누리 URL 패턴이 없어 O열에 '미부착' 입력 (P, Q열 패스)") else: print(f"[행 {row}] 에러: 페이지 응답 코드 {response.status_code}") except Exception as e: print(f"[행 {row}] 크롤링 실패 (오류 내용): {e}") # 20행마다 진행상황을 파일에 임시 저장 if row % 20 == 0: wb.save(output_path) print(f"--- 중간 저장 완료 ({row}행까지 진행) ---") # 4. 최종 결과 파일 저장 wb.save(output_path) print(f"\n모든 작업이 완료되었습니다! 결과가 '{output_path}'에 저장되었습니다.") if __name__ == "__main__": # 사용자의 실제 파일 경로에 맞게 미리 세팅해 두었습니다. input_filename = r"D:\01.프로젝트\DB수집\인천광역시\인천광역시_홈페이지_사이트_결과.xlsx" output_filename = r"D:\01.프로젝트\DB수집\인천광역시\인천광역시_홈페이지_사이트_결과_r1.xlsx" if os.path.exists(input_filename): crawl_and_update_excel(input_filename, output_filename) else: print(f"⚠️ '{input_filename}' 파일을 찾을 수 없습니다.") print("경로나 파일명이 올바른지 다시 한번 확인해주세요.")