공공기관2 작업 중. _temp 몽타주(재생성가능)는 제외. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
79 lines
3.2 KiB
Python
79 lines
3.2 KiB
Python
import pandas as pd
|
|
import requests
|
|
from bs4 import BeautifulSoup
|
|
import re
|
|
import time
|
|
|
|
# 1. 파일 불러오기
|
|
file_name = r"C:\Users\hehih\Downloads\인천관역시\인천광역시_홈페이지_사이트_r1.xlsx"
|
|
sheet_name = "Sitemap"
|
|
|
|
print("엑셀 파일을 읽어오는 중입니다...")
|
|
df = pd.read_excel(file_name, sheet_name=sheet_name, header=None)
|
|
|
|
# 웹사이트 접속 차단 방지 설정
|
|
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("URL 순차 파싱을 시작합니다...")
|
|
|
|
# 2. 각 행을 순회하며 데이터 추출 및 입력
|
|
for index, row in df.iterrows():
|
|
if index < 2: # 안내문구 및 헤더 건너뛰기
|
|
continue
|
|
|
|
url = row[8] # 8번 인덱스 = I열 (주소url)
|
|
|
|
if pd.isna(url) or not str(url).startswith('http'):
|
|
continue
|
|
|
|
print(f"[{index+1}/{len(df)}] 파싱 중: {url}")
|
|
|
|
try:
|
|
response = requests.get(url, headers=headers, timeout=10)
|
|
|
|
if response.status_code == 200:
|
|
soup = BeautifulSoup(response.text, 'html.parser')
|
|
|
|
# 태그 찾기
|
|
target_div = soup.find('div', class_='board-page-total')
|
|
|
|
# [조건문] 태그가 존재하는 경우 (게시판)
|
|
if target_div:
|
|
div_text = target_div.get_text()
|
|
match = re.search(r'전체\s*([\d,]+)\s*건', div_text)
|
|
|
|
if match:
|
|
total_count = match.group(1).replace(',', '')
|
|
df.at[index, 9] = "게시판" # J열
|
|
df.at[index, 10] = int(total_count) # K열
|
|
print(f" => [게시판 확인] 건수: {total_count}건")
|
|
else:
|
|
df.at[index, 9] = "게시판(양식 다름)"
|
|
df.at[index, 10] = "-"
|
|
print(" => 태그는 있으나 건수 형식이 다릅니다.")
|
|
|
|
# [조건문 수정] 태그가 없는 경우 (일반 페이지 등)
|
|
else:
|
|
df.at[index, 9] = "페이지" # J열에 일반페이지 입력
|
|
df.at[index, 10] = "" # K열은 대시(-) 처리 (또는 0 입력 가능)
|
|
print(" => [일반페이지] 'board-page-total' 태그 없음")
|
|
|
|
else:
|
|
df.at[index, 9] = "접속실패"
|
|
df.at[index, 10] = f"에러({response.status_code})"
|
|
print(f" => 접속 실패 (상태코드: {response.status_code})")
|
|
|
|
except Exception as e:
|
|
df.at[index, 9] = "접속오류"
|
|
df.at[index, 10] = "오류"
|
|
print(f" => 오류 발생: {e}")
|
|
|
|
# 서버 차단 방지를 위해 0.5초씩 휴식
|
|
time.sleep(0.5)
|
|
|
|
# 3. 원래 양식을 유지하며 새 엑셀 파일로 저장
|
|
output_file = "인천광역시_홈페이지_사이트_결과.xlsx"
|
|
df.to_excel(output_file, index=False, header=False)
|
|
print(f"\n모든 작업이 완료되었습니다! 결과가 '{output_file}' 파일로 저장되었습니다.") |