-
Notifications
You must be signed in to change notification settings - Fork 0
/
Crawling_system.py
249 lines (220 loc) Β· 10.6 KB
/
Crawling_system.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# webdriver-manager μ€μΉ
# ! pip install webdriver-manager
# Webdriver import
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
# Crawling import
import requests
from bs4 import BeautifulSoup
import time
from datetime import datetime
import ray
# data import
import re
import json
from itertools import chain
### DB connect import
import pymysql
import pandas as pd
from tqdm import tqdm
class CrawlingSystem():
def setup_chrome_driver(self):
chrome_options = Options()
chrome_options.add_argument("--headless") # Run Chrome in headless mode (without GUI)
chrome_options.add_argument('--blink-settings=imagesEnabled=false') # Not load image
# install Chrome webdriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
return driver
'''
κ° μ¬μ΄νΈμμ ν¬λ‘€λ§νλ ν¨μ.
νμμ΄ + μ°κ΄μ΄ λ¨μ΄κ° λ€μ΄μ€λ©΄ forλ¬ΈμΌλ‘ κ° λ¨μ΄ κ²°κ³Όλ₯Ό νμ±ν ν search_listλ₯Ό λ°ν
- input
driver(webdriver) : selenium.webdriver.chrome.webdriver
search_word(str) : νμμ΄
related_word(str) : μ°κ΄μ΄
- output
search_list(list) : νμμ΄+μ°κ΄μ΄ κ²μκ²°κ³Ό 리μ€νΈ(nestd dict)
{ search_word(str) : νμμ΄
related_word(str) : μ°κ΄μ΄
title(str) : μ λͺ©
url(str) : ν΄λΉ url
date(str) : μμ±μΌ(yyyy-mm-dd νμ)
comment_cnt(int) : λκΈμ }
'''
def fm_crawling(self, driver:webdriver, search_word: str, related_word: str):
'''
/www.fmkorea.com ν¬λ‘€λ§
κ²μμ΄ μ‘°κ±΄ μμ
'''
search_list = []
url = f'https://www.fmkorea.com/search.php?act=IS&is_keyword={search_word}+{related_word}'
driver.get(url)
time.sleep(1)
soup = BeautifulSoup(driver.page_source, 'html.parser')
search_in_commu = soup.find('ul', class_="searchResult")
for search in search_in_commu:
search_dict = dict()
if search != ' ':
if search_in_commu.find('a') is not None:
title = search.find('a').get_text().split(']')
title = ' '.join(']'.join(title[1:]).split(' '))
url = f"https://www.fmkorea.com{search.find('a')['href']}"
date = search.find('span', class_ = 'time').get_text().split(' ')[0] # νμ yyyy-mm-dd
try:
comment_cnt = int(search.find('em').get_text())
except AttributeError: # λκΈ μλ κ²½μ°
comment_cnt = 0
search_dict['search_word'] = search_word
search_dict['related_word'] = related_word
search_dict['title'] = title
search_dict['url'] = url
search_dict['date'] = date
search_dict['comment_cnt'] = comment_cnt
search_list.append(search_dict)
return search_list
def pp_crawling(self, driver:webdriver, search_word: str, related_word: str):
'''
www.ppomppu.co.kr ν¬λ‘€λ§
κ²μμ΄ λ μ€ νκ°λΌλ νκΈ2μ, μμ΄ 4μ μ΄νλ©΄ κ²μ μλ¨
νΉμνκΈ μ·¨κΈX (μͺ,λ·,..)
'''
if (len(bytes(search_word, 'euc-kr')) < 4) or (len(bytes(related_word, 'euc-kr')) < 4):
return
elif len(search_word) *2 != len(bytes(search_word, 'euc-kr')) or len(related_word) *2 != len(bytes(related_word, 'euc-kr')):
if re.match("^[κ°-ν£]+$", (search_word and related_word)):
if len(search_word) ==2 or len(related_word) == 2:
return
else:
search_list = []
url = f'https://www.ppomppu.co.kr/search_bbs.php?bbs_cate=2&keyword={search_word}+{related_word}'
driver.get(url)
time.sleep(1)
soup = BeautifulSoup(driver.page_source, 'html.parser')
search_in_commu = soup.find_all('div', class_="content")
for search in search_in_commu:
search_dict = dict()
comment_cnt = int(search.find('font', class_ = 'comment-cnt').get_text())
search.find('a').font.decompose()
title = search.find('a').get_text()
url = f"https://www.ppomppu.co.kr{search.find('a')['href']}"
date = search.find('p', class_ = 'desc').select_one('span:nth-child(3)').string.split('.')
date = '-'.join(date) # yyyy-mm-dd νμ λ§μΆ°μ€
search_dict['search_word'] = search_word
search_dict['related_word'] = related_word
search_dict['title'] = title
search_dict['url'] = url
search_dict['date'] = date
search_dict['comment_cnt'] = comment_cnt
search_list.append(search_dict)
return search_list
def hu_crawling(self, driver:webdriver, search_word: str, related_word: str):
'''
http://web.humoruniv.com ν¬λ‘€λ§
main siteμμ κ²μ(κ²μ λ§ν¬μμ λ°λ‘ μλ¨)
κ²μμ΄ λ μ€ 1κ°λΌλ νκΈ2μ, μμ΄ 4μ μ΄νλ©΄ κ²μ μλ¨
νΉμνκΈ μ·¨κΈX (μͺ,λ·,..)
'''
# νμμ΄ μ°κ΄μ΄ λ μ€ νλλΌλ 4byte μ΄νλ©΄ κ²μμλ¨ & νκΈ 2μμΌλ, νλλΌλ μ΄μλ¬Έμ(μͺ)μ΄λ©΄ μλ¨
if (len(bytes(search_word, 'euc-kr')) < 4) or (len(bytes(related_word, 'euc-kr')) < 4):
return
elif len(search_word) *2 != len(bytes(search_word, 'euc-kr')) or len(related_word) *2 != len(bytes(related_word, 'euc-kr')):
if re.match("^[κ°-ν£]+$", (search_word and related_word)):
if len(search_word) ==2 or len(related_word) == 2:
return
else:
search_list = []
url = "http://web.humoruniv.com/main.html"
driver.get(url)
time.sleep(1)
x_path_search = '//*[@id="search_text"]'
searchbox = driver.find_element(By.XPATH, x_path_search)
searchbox.click()
element = driver.find_element(By.NAME, "search_text")
element.send_keys(f'{search_word} {related_word}')
element.submit()
soup = BeautifulSoup(driver.page_source, 'html.parser')
search_in_commu = soup.find_all('td', style ="word-break: break-all;")
for search in search_in_commu:
search_dict = dict()
title = search.find('a').get_text()
url = search.find('a')['href']
date = search.find('font').get_text().split(' ')[0]
comment_cnt = search.find('font', color = 'green').get_text().split(' ')[1]
search_dict['search_word'] = search_word
search_dict['related_word'] = related_word
search_dict['title'] = title
search_dict['url'] = url
search_dict['date'] = date
search_dict['comment_cnt'] = comment_cnt
search_list.append(search_dict)
return search_list
def mp_crawling(self, driver:webdriver, search_word: str, related_word: str):
'''
https://mlbpark.donga.com ν¬λ‘€λ§
κ²μμ΄ μ‘°κ±΄ X
'''
url = f'https://mlbpark.donga.com/mp/b.php?search_select=sct&search_input={search_word}+{related_word}&x=0&y=0&select=sct&m=search&b=bullpen&query={search_word}+{related_word}'
driver.get(url)
time.sleep(1)
soup = BeautifulSoup(driver.page_source, 'html.parser')
search_in_commu = soup.select('tr')
search_list = []
for search in search_in_commu:
search_dict = dict()
if search.find('a') is not None:
title = search.find('a', class_ = 'txt').get_text()
url = search.find('a', class_ = 'txt')['href']
date = search.find('span', class_ = 'date').get_text()
if ':' in date: # λΉμΌ μμ± λ΄μ©μ μκ°μΌλ‘ νμλμ΄ μ€λ λ μ§λ‘ λ£μ΄μ€
date = datetime.now().date()
try:
comment_cnt = search.find('span', class_ = 'replycnt').get_text()
comment_cnt = int(re.sub('[\]\[]', '', comment_cnt))
except AttributeError:
comment_cnt = 0
search_dict['search_word'] = search_word
search_dict['related_word'] = related_word
search_dict['title'] = title
search_dict['url'] = url
search_dict['date'] = date
search_dict['comment_cnt'] = comment_cnt
search_list.append(search_dict)
return search_list
def word_load(path):
with open(path, 'r', encoding= 'utf-8-sig') as f:
json_data = json.load(f)
return json_data
def main():
start = time.time()
path = "*"
json_data = word_load(path)
print(f"json_data λ‘λμκ° =>>> {time.time() - start}")
crawling_system = CrawlingSystem()
driver = crawling_system.setup_chrome_driver()
start = time.time()
crawling_data = []
for search_word in json_data:
word_time = time.time()
for related_word in json_data[search_word]:
if (re.match("^[κ°-ν£a-zA-Z0-9_ ]+$", search_word) and re.match("^[κ°-ν£a-zA-Z0-9_ ]+$", related_word)):
search_list = crawling_system.pp_crawling(driver, search_word, related_word)
crawling_data.append(search_list)
search_list = crawling_system.fm_crawling(driver, search_word, related_word)
crawling_data.append(search_list)
search_list = crawling_system.hu_crawling(driver, search_word, related_word)
crawling_data.append(search_list)
search_list = crawling_system.mp_crawling(driver, search_word, related_word)
crawling_data.append(search_list)
break
print(f'{search_word} search fin ==> {time.time() - word_time}sec')
crawling_df = pd.DataFrame(list(chain.from_iterable(crawling_data)))
print(f"{len(crawling_df)} κ²μμκ° =>>> {time.time() - start}")
print(crawling_df)
return crawling_df
if __name__ == "__main__":
main()
## search_word κ²μμκ° =>>> search_word νλμ νκ· 100 sec