-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoryeong-gun.py
133 lines (100 loc) · 4.47 KB
/
Goryeong-gun.py
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
125
126
127
128
129
130
131
132
133
import re
import os
import sys
import time
import requests
import urllib.parse
from bs4 import BeautifulSoup, Comment
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import babya_server
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options)
try:
region = "111030"
current_list = list()
result_data = []
site_url = requests.get(f"{babya_server}/policy/site", params={"region": region})
response_data = site_url.json()
base_url = response_data["data"]["policySiteUrl"]
format_url = base_url.split("/index")[0]
collected_site_data = requests.get(f"{babya_server}/policy/catalog", params={"site": base_url})
collected_list = [item["pageId"] for item in collected_site_data.json()["data"]]
url = f"{format_url}/contents.do?IDX=47"
driver.get(url)
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
for i in soup.select("aside.Wrap_lnb_box > div.lnb_box > div.lnb_menu > ul.lnb_menu_ul > li.lnb_choice1 > ul > li > a"):
id_item = i.get("href").split("?IDX=")[1]
current_list.append(id_item)
page_list = set(current_list) - set(collected_list)
for page_id in page_list:
page_url = f"{format_url}/contents.do?IDX={page_id}"
driver.get(page_url)
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
data_dict = {
"title": None,
"content": None,
"editDate": None,
"pageId": None,
"site": None,
"page": None
}
styles = []
for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):
comment.extract()
for meta in soup.select("html > head > meta"):
if meta.get("charset"):
styles.append(str(meta))
for link in soup.select("html > head > link"):
if link.get("rel")[0] == "stylesheet":
link_url = link.get("href")
link["href"] = urllib.parse.urljoin(base_url, link_url)
styles.append(str(link))
# 가장 중요한 style
styles.append('<link href="https://www.goryeong.go.kr/health/css/health_sub_common.css" rel="stylesheet" type="text/css" />')
for title in soup.select("div.subTitle_wrap > h3"):
data_dict["title"] = title.get_text()
for content in soup.select("div.subContents"):
for tag in content.find_all("div", class_="subTitle_wrap"):
tag.extract()
for img in content.find_all('img'):
img_url = img.get("src")
if img_url:
img["src"] = urllib.parse.urljoin(base_url, img_url)
for a in content.find_all("a", href=True):
file_url = a['href']
a['href'] = urllib.parse.urljoin(base_url, file_url)
styles_str = "".join(styles)
content_str = re.sub(r'[\s\u00A0-\u00FF]+', " ", str(content))
head_content = f"<head>{styles_str}</head>"
body_content = f"<body>{content_str}</body>"
html_content = f"<!DOCTYPE html><html>{head_content}{body_content}</html>"
data_dict["content"] = html_content
# 최근수정일 없음
data_dict["pageId"] = page_id
data_dict["site"] = base_url
data_dict["page"] = page_url
if all(data_dict[key] is not None for key in ["title", "content"]):
result_data.append(data_dict)
if (len(result_data) > 0):
print(f"크롤링한 페이지 개수: [{len(result_data)}]")
policy = requests.post(f"{babya_server}/policy", json=result_data)
print(policy.status_code)
print(policy.text)
else:
print("아직 새로운 정책이 업데이트 되지 않았습니다.")
except Exception as e:
print(f"Error: {e}")
driver.close()
sys.exit()
finally:
driver.close()
sys.exit()
while True:
pass