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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
import urllib.parse
import urllib3
import requests
import argparse
import re
from bs4 import BeautifulSoup
from datetime import datetime
# SSL 경고 무시
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
SEARCH_URL = "https://www.allproductkorea.or.kr/products/search"
class AllProductKoreaScraper:
def __init__(self):
self.session = requests.Session()
self.session.verify = False # SSL 검증 비활성화
self.headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
def convert_to_original_image(self, image_url: str) -> str:
"""작은 이미지 URL을 원본 이미지 URL로 변환"""
if not image_url or not image_url.strip():
return image_url
# Firebase Storage URL인 경우만 변환
if "firebasestorage.googleapis.com" not in image_url:
return image_url
try:
# 1단계: _숫자_w 패턴 제거
step1 = re.sub(r'_\d+_w(?=\.[a-zA-Z]{2,5})', '', image_url)
# 2단계: 토큰 파라미터 제거
step2 = re.sub(r'&token=[a-f0-9\-]+', '', step1)
return step2
except Exception as e:
print(f"이미지 URL 변환 오류: {e} (URL: {image_url})", file=sys.stderr)
return image_url
def test_image_accessibility(self, image_url: str) -> dict:
"""이미지 URL이 실제로 로드되는지 테스트"""
test_result = {
"url": image_url,
"accessible": False,
"status_code": None,
"content_type": None,
"content_length": None,
"error": None
}
if not image_url or not image_url.strip():
test_result["error"] = "URL이 비어있음"
return test_result
try:
response = self.session.head(image_url, timeout=10)
test_result["status_code"] = response.status_code
test_result["accessible"] = response.status_code == 200
test_result["content_type"] = response.headers.get("content-type", "")
test_result["content_length"] = response.headers.get("content-length")
if test_result["content_length"]:
test_result["content_length"] = int(test_result["content_length"])
except Exception as e:
test_result["error"] = str(e)
return test_result
def build_search_url(self, main_keyword: str, sub_keyword: str = "", page: int = 1, size: int = 10) -> str:
"""검색 URL 생성"""
q = json.dumps({
"mainKeyword": main_keyword,
"subKeyword": sub_keyword
}, ensure_ascii=False)
params = {
"q": q,
"page": page,
"size": size
}
return f"{SEARCH_URL}?{urllib.parse.urlencode(params)}"
def fetch_html(self, url: str) -> str:
"""HTML 페이지 가져오기"""
response = self.session.get(url, headers=self.headers, timeout=30)
response.raise_for_status()
response.encoding = 'utf-8'
return response.text
def extract_pagination_info(self, soup: BeautifulSoup) -> dict:
"""페이지네이션 정보 추출"""
pagination_info = {
"current_page": 1,
"total_pages": 1,
"page_size": 10,
"total_count": 0,
"result_count": 0,
"has_next": False,
"has_prev": False
}
try:
# 총 결과 수 추출
total_element = soup.select_one(".pl_total span")
if total_element:
total_text = total_element.get_text(strip=True)
# "총 : 30건" 형태에서 숫자 추출
total_match = re.search(r'총\s*:\s*(\d+)건', total_text)
if total_match:
pagination_info["total_count"] = int(total_match.group(1))
# 페이지 정보 추출
page_info = soup.select_one(".per_pageinfo")
if page_info:
page_text = page_info.get_text(strip=True)
# "총 3페이지" 형태에서 숫자 추출
page_match = re.search(r'총\s*(\d+)페이지', page_text)
if page_match:
pagination_info["total_pages"] = int(page_match.group(1))
# 현재 페이지 추출 (스크립트에서)
script_tags = soup.find_all('script')
for script in script_tags:
if script.string and 'pagination' in script.string:
# JavaScript에서 페이지 정보 추출 시도
page_match = re.search(r'"page"\s*:\s*(\d+)', script.string)
if page_match:
pagination_info["current_page"] = int(page_match.group(1))
size_match = re.search(r'"size"\s*:\s*(\d+)', script.string)
if size_match:
pagination_info["page_size"] = int(size_match.group(1))
count_match = re.search(r'"resultCount"\s*:\s*(\d+)', script.string)
if count_match:
pagination_info["result_count"] = int(count_match.group(1))
# 이전/다음 페이지 존재 여부
pagination_info["has_prev"] = pagination_info["current_page"] > 1
pagination_info["has_next"] = pagination_info["current_page"] < pagination_info["total_pages"]
except Exception as e:
print(f"페이지네이션 정보 추출 오류: {e}", file=sys.stderr)
return pagination_info
def extract_search_metadata(self, soup: BeautifulSoup) -> dict:
"""검색 메타데이터 추출"""
metadata = {
"title": "",
"breadcrumb": [],
"search_input_placeholder": "",
"page_description": ""
}
try:
# 페이지 제목
title_element = soup.select_one("title")
if title_element:
metadata["title"] = title_element.get_text(strip=True)
# 브레드크럼
breadcrumb_elements = soup.select(".loc_wrap li")
for element in breadcrumb_elements:
text = element.get_text(strip=True)
if text and text != "홈":
metadata["breadcrumb"].append(text)
# 검색 입력창 플레이스홀더
search_input = soup.select_one("#searchText")
if search_input:
metadata["search_input_placeholder"] = search_input.get("placeholder", "")
# 페이지 설명
h3_element = soup.select_one(".h3_wrap h3")
if h3_element:
metadata["page_description"] = h3_element.get_text(strip=True)
except Exception as e:
print(f"메타데이터 추출 오류: {e}", file=sys.stderr)
return metadata
def extract_products(self, soup: BeautifulSoup) -> list:
"""제품 리스트 추출"""
products = []
for li in soup.select(".spl_list li[data-prd-no]"):
try:
product = {
"prdNo": li.get("data-prd-no", "").strip(),
"barcode": "",
"name": "",
"image": "",
"categoryPath": "",
"categoryHierarchy": [],
"link": ""
}
# 이미지 URL (원본 이미지로 변환)
img = li.select_one(".spl_img img")
if img:
original_image_url = img.get("src", "")
# 작은 이미지를 원본 이미지로 변환
converted_image_url = self.convert_to_original_image(original_image_url)
product["image"] = converted_image_url
# 원본과 변환된 URL이 다르면 둘 다 저장
if original_image_url != converted_image_url:
product["original_small_image"] = original_image_url
product["image_conversion_applied"] = True
else:
product["image_conversion_applied"] = False
# 바코드와 제품명
pt = li.select_one(".spl_pt")
if pt:
barcode_elem = pt.select_one("em")
if barcode_elem:
product["barcode"] = barcode_elem.get_text(strip=True)
name_elem = pt.select_one("strong")
if name_elem:
product["name"] = name_elem.get_text(strip=True)
# 카테고리 경로
pm = li.select_one(".spl_pm")
if pm:
category_path = pm.get_text(strip=True)
product["categoryPath"] = category_path
# 카테고리를 배열로도 저장
if category_path:
product["categoryHierarchy"] = [cat.strip() for cat in category_path.split(">")]
# 링크 (추정)
if product["prdNo"]:
product["link"] = f"/products/info/korcham/{product['prdNo']}"
products.append(product)
except Exception as e:
print(f"제품 정보 추출 오류: {e}", file=sys.stderr)
continue
return products
def scrape(self, main_keyword: str, sub_keyword: str = "", page: int = 1, size: int = 10) -> dict:
"""메인 스크래핑 함수"""
url = self.build_search_url(main_keyword, sub_keyword, page, size)
print(f"검색 파라미터:", file=sys.stderr)
print(f" - 주요 키워드: {main_keyword}", file=sys.stderr)
print(f" - 보조 키워드: {sub_keyword}", file=sys.stderr)
print(f" - 페이지: {page}", file=sys.stderr)
print(f" - 사이즈: {size}", file=sys.stderr)
print(f"요청 URL: {url}", file=sys.stderr)
html = self.fetch_html(url)
print(f"HTML 가져오기 완료 ({len(html):,} bytes)", file=sys.stderr)
soup = BeautifulSoup(html, "lxml")
# 모든 데이터 추출
products = self.extract_products(soup)
pagination = self.extract_pagination_info(soup)
metadata = self.extract_search_metadata(soup)
print(f"스크래핑 결과: {len(products)}개 제품", file=sys.stderr)
# 이미지 URL 변환 및 접근성 테스트
image_test_results = []
conversion_count = 0
accessible_count = 0
for i, product in enumerate(products[:3]): # 처음 3개 제품만 테스트
if product.get("image"):
test_result = self.test_image_accessibility(product["image"])
test_result["product_index"] = i
test_result["product_name"] = product.get("name", "이름 없음")
test_result["conversion_applied"] = product.get("image_conversion_applied", False)
if test_result["conversion_applied"]:
conversion_count += 1
if test_result["accessible"]:
accessible_count += 1
image_test_results.append(test_result)
content_length = test_result.get('content_length') or 0
status = "OK" if test_result['accessible'] else "FAIL"
print(f"이미지 테스트 [{i+1}] {product.get('name', '이름없음')[:20]}: {status} ({content_length:,} bytes)", file=sys.stderr)
if image_test_results:
print(f"URL 변환: {conversion_count}/{len(image_test_results)}개", file=sys.stderr)
print(f"접근 가능: {accessible_count}/{len(image_test_results)}개", file=sys.stderr)
# 결과 구성
result = {
"timestamp": datetime.now().isoformat(),
"request": {
"url": url,
"parameters": {
"mainKeyword": main_keyword,
"subKeyword": sub_keyword,
"page": page,
"size": size
}
},
"metadata": metadata,
"pagination": pagination,
"products": {
"count": len(products),
"items": products
},
"image_tests": {
"tested_count": len(image_test_results),
"conversion_count": conversion_count,
"accessible_count": accessible_count,
"results": image_test_results
},
"summary": {
"scraped_count": len(products),
"total_available": pagination.get("total_count", 0),
"current_page": pagination.get("current_page", page),
"total_pages": pagination.get("total_pages", 1),
"has_more_pages": pagination.get("has_next", False)
}
}
return result
def main():
parser = argparse.ArgumentParser(
description="AllProductKorea.or.kr 제품 검색 스크래퍼",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
사용 예시:
python allproductkorea_scraper.py "빙그레 더단백"
python allproductkorea_scraper.py "삼양라면" --page 2 --size 20
python allproductkorea_scraper.py "커피" --sub-keyword "원두" --page 1 --size 50
python allproductkorea_scraper.py --url "https://www.allproductkorea.or.kr/products/search?q=..."
"""
)
# 파라미터 그룹 1: 검색어 방식
search_group = parser.add_argument_group('검색어 파라미터')
search_group.add_argument('main_keyword', nargs='?', help='주요 검색어')
search_group.add_argument('--sub-keyword', '-s', default='', help='보조 검색어 (기본값: 빈 문자열)')
search_group.add_argument('--page', '-p', type=int, default=1, help='페이지 번호 (기본값: 1)')
search_group.add_argument('--size', '-z', type=int, default=10, help='페이지당 결과 수 (기본값: 10)')
# 파라미터 그룹 2: URL 직접 입력
url_group = parser.add_argument_group('URL 직접 입력')
url_group.add_argument('--url', '-u', help='완성된 검색 URL 직접 입력')
# 출력 옵션
output_group = parser.add_argument_group('출력 옵션')
output_group.add_argument('--pretty', action='store_true', help='JSON 출력을 예쁘게 포맷')
output_group.add_argument('--output', '-o', help='결과를 파일로 저장')
args = parser.parse_args()
# 파라미터 검증
if not args.url and not args.main_keyword:
print("오류: 검색어 또는 URL을 제공해야 합니다.", file=sys.stderr)
parser.print_help()
sys.exit(1)
try:
scraper = AllProductKoreaScraper()
if args.url:
# URL에서 파라미터 추출
parsed_url = urllib.parse.urlparse(args.url)
query_params = urllib.parse.parse_qs(parsed_url.query)
if 'q' in query_params:
q_data = json.loads(query_params['q'][0])
main_keyword = q_data.get('mainKeyword', '')
sub_keyword = q_data.get('subKeyword', '')
else:
main_keyword = ''
sub_keyword = ''
page = int(query_params.get('page', [1])[0])
size = int(query_params.get('size', [10])[0])
else:
main_keyword = args.main_keyword
sub_keyword = args.sub_keyword
page = args.page
size = args.size
# 스크래핑 실행
result = scraper.scrape(main_keyword, sub_keyword, page, size)
# 결과 출력
if args.pretty:
json_output = json.dumps(result, ensure_ascii=False, indent=2)
else:
json_output = json.dumps(result, ensure_ascii=False)
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(json_output)
print(f"결과를 {args.output}에 저장했습니다.", file=sys.stderr)
else:
print(json_output)
except Exception as e:
print(f"오류 발생: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
|