728x90
서울 중구청 조직도를 파싱처리하는 Python 코드이다.
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
|
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
def crawl_orgchart_guchung(url):
# 요청 및 응답 확인
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
# 데이터 저장 리스트
data = []
# 조직도의 범주에 해당하는 코드를 찾아낸다.
scope = soup.find("div", class_="jg_organization_chart")
# print(scope)
# 모든 href 속성값 추출
href_values = [a.get('href') for a in scope.find_all('a', href=True)]
# '#' 또는 'javascript:' 를 포함하지 않는 href만 필터링하고,
# 'https://www.junggu.seoul.kr'이 포함되지 않으면 추가하여 완전한 URL로 반환
base_url = "https://www.junggu.seoul.kr"
filtered_href = [
href if href.startswith("https://www.junggu.seoul.kr") else base_url + href
for href in href_values
if not href.startswith(("#", "javascript:"))
]
# "dong" 포함 여부에 따라 분리
dong_href = [href for href in filtered_href if "dong" in href]
non_dong_href = [href for href in filtered_href if "dong" not in href]
data = [non_dong_href, dong_href]
return data
def crawl_orgchart_main(url):
# 요청 및 응답 확인
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
# 데이터 저장 리스트
data = []
# 테이블 찾기
tables = soup.find_all("div",class_="tableScroll")
for table in tables:
# print(table)
rows = table.select("tbody tr")
# print(rows)
for row in rows:
team = row.find("th").text.strip()
cols = row.find_all("td")
if len(cols) >= 3: # 필요한 열 개수 확인
position = cols[0].text.strip()
phone = cols[1].text.strip()
duty = cols[2].text.strip()
data.append([team, position, phone, duty])
# 데이터프레임 생성
columns = ["부서명", "직위", "전화번호","담당업무"]
df = pd.DataFrame(data, columns=columns)
return df
def crawl_orgchart_dong(url):
# 요청 및 응답 확인
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
# 데이터 저장 리스트
data = []
# 조직도의 범주에 해당하는 코드를 찾아낸다.
scope = soup.find("div", class_="member_list")
# 테이블 찾기
rows = scope.select("table tbody tr")
for row in rows:
team = row.find("th").text.strip()
cols = row.find_all("td")
if len(cols) >= 3: # 필요한 열 개수 확인
position = " ".join(cols[0].stripped_strings)
phone = cols[1].get_text(separator=" ").strip()
duty = cols[2].get_text(separator=" ").strip()
data.append([team, position, phone, duty])
# 데이터프레임 생성
columns = ["부서명", "직위", "전화번호", "담당업무"]
df = pd.DataFrame(data, columns=columns)
return df
if __name__ == "__main__":
url_main = "https://www.junggu.seoul.kr/content.do?cmsid=14066"
df_main = crawl_orgchart_guchung(url_main)
# 모든 URL에서 데이터 크롤링
dataframe_main = [crawl_orgchart_main(url) for url in df_main[0]]
# 데이터프레임 병합
df_combined = pd.concat(dataframe_main, ignore_index=True)
# 두 데이터프레임을 합치기
if not df_combined.empty:
print(df_combined)
df_combined.to_csv("서울중구청.csv", index=False, encoding="utf-8-sig")
dataframe_dong = [crawl_orgchart_dong(url) for url in df_main[1]]
# 데이터프레임 병합
df_dong_combined = pd.concat(dataframe_dong, ignore_index=True)
# 두 데이터프레임을 합치기
if not df_dong_combined.empty:
print(df_dong_combined)
df_dong_combined.to_csv("서울중구청_동주민센터.csv", index=False, encoding="utf-8-sig")
|
총 3단계의 과정으로 진행하는 코드이다.
자료를 추출하는 과정에 대한 설명은 생략한다.
728x90
'Web 크롤링 > Python Crawling' 카테고리의 다른 글
강동구청 조직도 크롤링 (0) | 2025.03.02 |
---|---|
종로구청 조직도 크롤링 (0) | 2025.03.01 |
[Python] 종로구청 동주민센터 크롤링 (0) | 2025.02.18 |
정부(행정안전부) 주소 검증 (0) | 2024.04.20 |
파이썬 selenium CentOS 7 환경설정 및 juso.go.kr 자료 파싱처리 (0) | 2024.03.25 |