-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2001 lines (1740 loc) · 105 KB
/
Copy pathapp.py
File metadata and controls
2001 lines (1740 loc) · 105 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import re
import uuid
import pandas as pd
from flask import Flask, render_template, request, jsonify, send_file, session
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from urllib.parse import quote_plus
import io
import threading
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-here-change-in-production')
# 세션별 크롤링 결과 저장 (session_id -> {results, status, stop_flag})
user_sessions = {}
# 제외할 사이트 목록 (정확한 도메인 매칭)
EXCLUDE_DOMAINS = [
# 네이버/다음/카카오
"naver.com", "naver.me", "daum.net", "kakao.com",
# 블로그/커뮤니티 (정확한 도메인)
"tistory.com", "blog.me", "brunch.co.kr", "medium.com",
"velog.io", "notion.so", "notion.site",
"dcinside.com", "clien.net", "ruliweb.com", "fmkorea.com",
# 채용사이트 (제외하지 않음 - 크롤링 대상)
# "saramin.co.kr", "jobkorea.co.kr", "incruit.com",
# "wanted.co.kr", "jobplanet.co.kr", "catch.co.kr",
# 쇼핑몰
"gmarket.co.kr", "11st.co.kr", "coupang.com", "auction.co.kr",
"aliexpress.com", "amazon.com", "ebay.com",
# 해외 도매
"alibaba.com", "made-in-china.com", "globalsources.com",
# 소셜미디어
"youtube.com", "facebook.com", "instagram.com",
"twitter.com", "linkedin.com",
# 위키/백과
"wikipedia.org", "namu.wiki", "terms.naver.com",
# 정부/공공
"go.kr",
]
def is_valid_company_url(url):
"""회사 웹사이트로 적합한 URL인지 확인 (더 정교한 필터링)"""
url_lower = url.lower()
# 정확한 도메인 매칭
for domain in EXCLUDE_DOMAINS:
# 도메인이 URL에 정확히 포함되어 있는지 확인
if domain in url_lower:
return False
# 블로그 패턴 제외 (blog가 URL 경로에 있는 경우)
if "/blog/" in url_lower or "/cafe/" in url_lower:
return False
# 뉴스 기사 패턴 제외 (article, news 경로)
if "/article/" in url_lower or "/news/" in url_lower:
return False
return True
def setup_driver():
print("[드라이버 초기화] 시작...")
chrome_options = Options()
# Railway/Docker 환경 감지
is_railway = os.environ.get('RAILWAY_ENVIRONMENT') is not None
is_docker = os.path.exists('/usr/bin/google-chrome')
is_windows = os.name == 'nt'
# Windows 환경에서 Chrome 경로 자동 감지
if is_windows:
chrome_paths = [
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
os.path.expanduser(r"~\AppData\Local\Google\Chrome\Application\chrome.exe"),
]
for path in chrome_paths:
if os.path.exists(path):
chrome_options.binary_location = path
print(f"[드라이버 초기화] Chrome 경로 발견: {path}")
break
else:
print("[드라이버 초기화] 경고: Chrome 경로를 찾지 못했습니다. 시스템 기본 경로 사용")
# Docker 환경
elif is_docker:
chrome_options.binary_location = '/usr/bin/google-chrome'
# 서버 환경(Railway/Docker)에서는 headless 모드 필수 (GUI 없음)
# 로컬 Windows 환경에서는 headless 비활성화 (브라우저 창이 보이도록)
if is_railway or is_docker:
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--single-process")
print("[드라이버 초기화] 서버 환경 감지: 헤드리스 모드 활성화")
else:
print("[드라이버 초기화] 로컬 환경: 헤드리스 모드 비활성화 (브라우저 창 표시)")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-setuid-sandbox")
chrome_options.add_argument("--remote-debugging-port=9222") # 디버깅 포트 추가
chrome_options.add_argument("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("[드라이버 초기화] ChromeDriver 준비 중...")
service = None
# 방법 1: 시스템 PATH에 있는 chromedriver 사용 시도
import shutil
chromedriver_in_path = shutil.which("chromedriver")
if chromedriver_in_path:
print(f"[드라이버 초기화] 시스템 PATH에서 ChromeDriver 발견: {chromedriver_in_path}")
service = Service(chromedriver_in_path)
print("[드라이버 초기화] 시스템 ChromeDriver 사용")
else:
# 방법 2: ChromeDriverManager 사용 (간단하고 직접적으로)
print("[드라이버 초기화] ChromeDriverManager로 드라이버 다운로드 시도...")
try:
# 직접 호출 (타임아웃은 외부에서 처리)
driver_path = ChromeDriverManager().install()
print(f"[드라이버 초기화] ChromeDriver 다운로드 완료: {driver_path}")
service = Service(driver_path)
except Exception as e:
print(f"[드라이버 초기화] ChromeDriverManager 실패: {e}")
import traceback
print(traceback.format_exc())
raise Exception(f"ChromeDriver 준비 실패: {e}\n해결 방법: ChromeDriver를 수동으로 설치하거나 시스템 PATH에 추가해주세요.\n다운로드: https://chromedriver.chromium.org/")
if service is None:
raise Exception("ChromeDriver 서비스를 초기화할 수 없습니다.")
print("[드라이버 초기화] 브라우저 시작 중...")
try:
print("[드라이버 초기화] Chrome 브라우저 시작 시도...")
driver = webdriver.Chrome(service=service, options=chrome_options)
print("[드라이버 초기화] 브라우저 시작 완료!")
# 브라우저가 정상적으로 시작되었는지 확인
driver.set_page_load_timeout(10)
driver.get("about:blank")
print("[드라이버 초기화] 브라우저 테스트 완료!")
return driver
except Exception as e:
error_msg = str(e)
print(f"[드라이버 초기화] 브라우저 시작 실패: {error_msg}")
import traceback
print(traceback.format_exc())
# 추가 디버깅 정보
if is_windows:
print("[드라이버 초기화] Windows 환경 디버깅 정보:")
print(f" - Chrome 경로: {chrome_options.binary_location if hasattr(chrome_options, 'binary_location') else '미설정'}")
print(f" - ChromeDriver 경로: {driver_path if 'driver_path' in locals() else '알 수 없음'}")
# Chrome이 설치되어 있는지 확인
import subprocess
try:
result = subprocess.run(['where', 'chrome'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
print(f" - 시스템에서 찾은 Chrome: {result.stdout.strip()}")
except:
pass
raise Exception(f"Chrome 브라우저 시작 실패: {error_msg}")
def get_naver_links(driver, keyword, pages=5, max_urls=0):
"""네이버 웹 검색에서 링크 수집 (목표 개수에 도달할 때까지 페이지 확장)"""
links = []
current_page = 1
max_pages = pages * 3 # 최대 3배까지 확장 가능
while current_page <= max_pages:
# 네이버 검색 URL 형식 (사용자가 제공한 형식 사용)
if current_page == 1:
url = f"https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query={quote_plus(keyword)}"
else:
start = (current_page - 1) * 10 + 1
url = f"https://search.naver.com/search.naver?nso=&page={current_page}&query={quote_plus(keyword)}&sm=tab_pge&ssc=tab.ur.all&start={start}"
print(f"[네이버] 페이지 {current_page} 크롤링 중: {url}")
driver.get(url)
time.sleep(3) # 페이지 로딩 대기
page_links_count = len(links)
# 1. 파워링크 광고에서 링크 추출 (가장 중요!)
print(f"[네이버] 파워링크 광고 링크 추출 시작...")
powerlink_selectors = [
".powerlink_area a",
".ad_powerlink a",
".power_link a",
"[class*='powerlink'] a",
"[class*='power_link'] a",
"[id*='powerlink'] a",
"[id*='power_link'] a",
".ad_area a",
".ad_section a",
]
for selector in powerlink_selectors:
try:
powerlink_ads = driver.find_elements(By.CSS_SELECTOR, selector)
print(f"[네이버] 파워링크 선택자 ({selector}): {len(powerlink_ads)}개 발견")
for ad in powerlink_ads:
try:
href = ad.get_attribute("href")
if href and href.startswith("http"):
# 네이버 링크 제외
if "naver.com" not in href.lower() and "search.naver" not in href.lower():
if is_valid_company_url(href):
if href not in links:
links.append(href)
print(f"[네이버] 파워링크 링크 추가: {href}")
except:
pass
except:
pass
# 2. 파워링크 영역에서 URL 텍스트 직접 추출
try:
powerlink_areas = driver.find_elements(By.CSS_SELECTOR, ".powerlink_area, .ad_powerlink, [class*='powerlink'], [class*='power_link']")
print(f"[네이버] 파워링크 영역 {len(powerlink_areas)}개 발견")
for area in powerlink_areas:
try:
# 영역 내의 모든 텍스트에서 URL 패턴 찾기
area_text = area.text
area_html = area.get_attribute("innerHTML") or ""
# URL 패턴 찾기 (http:// 또는 https://로 시작)
url_pattern = r'https?://[^\s<>"\']+[^\s<>"\'.,;!?]'
found_urls = re.findall(url_pattern, area_text + " " + area_html)
for found_url in found_urls:
# 네이버 링크 제외
if "naver.com" not in found_url.lower() and "search.naver" not in found_url.lower():
if is_valid_company_url(found_url):
if found_url not in links:
links.append(found_url)
print(f"[네이버] 파워링크 텍스트에서 URL 추출: {found_url}")
except:
pass
except:
pass
# 3. 네이버 웹 검색 결과의 다양한 선택자
print(f"[네이버] 일반 검색 결과 링크 추출 시작...")
selectors = [
"a.link_tit", "div.total_tit a", "a.total_tit", "a.title_link",
"div.web_item a.link", "div.lst_view a", "div.api_txt_lines a",
"div.total_wrap a", "li.bx a",
"a[href^='http']:not([href*='naver.com']):not([href*='search.naver'])",
]
for selector in selectors:
try:
results = driver.find_elements(By.CSS_SELECTOR, selector)
for res in results:
href = res.get_attribute("href")
if href and href.startswith("http") and is_valid_company_url(href):
if "naver.com" not in href and "search.naver" not in href:
if href not in links:
links.append(href)
except:
pass
print(f"[네이버] 페이지 {current_page}에서 {len(links) - page_links_count}개 링크 발견 (총 {len(links)}개)")
# 목표 개수에 도달했거나, 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if max_urls > 0 and len(links) >= max_urls:
break
# 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if current_page > pages and len(links) == page_links_count:
break
try:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
except:
pass
current_page += 1
return list(set(links))
def get_daum_links(driver, keyword, pages=5, max_urls=0):
"""다음 웹 검색에서 링크 수집 (목표 개수에 도달할 때까지 페이지 확장)"""
links = []
current_page = 1
max_pages = pages * 3 # 최대 3배까지 확장 가능
while current_page <= max_pages:
url = f"https://search.daum.net/search?w=web&q={quote_plus(keyword)}&p={current_page}"
driver.get(url)
time.sleep(2)
page_links_count = len(links)
# 다음 웹 검색 결과 선택자
selectors = [
"a.f_link_b", # 웹문서 제목 링크
"div.wrap_tit a", # 제목 링크
"a.link_txt", # 텍스트 링크
"div.c-tit a", # 컨텐츠 제목
"div.c-item a", # 아이템 링크
"a[href^='http']:not([href*='daum.net']):not([href*='kakao'])",
]
for selector in selectors:
try:
results = driver.find_elements(By.CSS_SELECTOR, selector)
for res in results:
href = res.get_attribute("href")
if href and href.startswith("http") and is_valid_company_url(href):
if "daum.net" not in href and "kakao.com" not in href:
if href not in links:
links.append(href)
except:
pass
# 목표 개수에 도달했거나, 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if max_urls > 0 and len(links) >= max_urls:
break
# 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if current_page > pages and len(links) == page_links_count:
break
try:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
except:
pass
current_page += 1
return list(set(links))
def get_saramin_company_links(driver, keyword, pages=10, max_urls=0):
"""사람인 사이트에서 회사 검색하여 회사 상세 페이지 링크 수집 (목표 개수에 도달할 때까지 페이지 확장)"""
links = []
current_page = 1
max_pages = pages * 3 # 최대 3배까지 확장 가능
try:
while current_page <= max_pages:
# 사람인 검색 URL (사용자가 제공한 형식 사용)
url = f"https://www.saramin.co.kr/zf_user/search?search_area=main&search_done=y&search_optional_item=n&searchType=search&searchword={quote_plus(keyword)}&recruitPage={current_page}"
print(f"[사람인] 페이지 {current_page} 크롤링 중: {url}")
driver.get(url)
time.sleep(3) # 페이지 로딩 대기
page_links_count = len(links)
# 사람인 검색 결과에서 회사 상세 페이지 링크 찾기
# 모든 방법을 병렬로 시도하여 최대한 많이 수집
try:
# 페이지가 완전히 로드될 때까지 대기
time.sleep(3)
# 페이지 소스 확인 (디버깅용)
page_source_snippet = driver.page_source[:2000] if len(driver.page_source) > 2000 else driver.page_source
print(f"[사람인] 페이지 소스 일부: {page_source_snippet[:500]}...")
# 페이지에 "/zf_user/company"가 있는지 확인
if "/zf_user/company" not in driver.page_source:
print(f"[사람인] 경고: 페이지에 '/zf_user/company' 링크가 없습니다!")
else:
print(f"[사람인] 페이지에 '/zf_user/company' 링크가 있습니다.")
# 방법 1: 모든 회사 관련 링크 찾기 (company-info/view 포함)
# /zf_user/company-info/view 링크도 수집 (이 링크를 따라가면 회사 상세 페이지로 갈 수 있음)
all_company_links = driver.find_elements(By.CSS_SELECTOR, "a[href*='/zf_user/company']")
print(f"[사람인] 방법1: {len(all_company_links)}개 링크 발견")
for link in all_company_links:
try:
href = link.get_attribute("href")
if href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
# 쿼리 파라미터는 유지 (csn 파라미터가 중요할 수 있음)
href_clean = href.split("#")[0].rstrip("/")
# /zf_user/company-info/view 링크 수집 (이 링크를 따라가면 회사 상세 페이지로 갈 수 있음)
if "/zf_user/company-info/view" in href_clean:
if href_clean not in links:
links.append(href_clean)
print(f"[사람인] 링크 추가 (company-info/view): {href_clean}")
# 정확히 /zf_user/company/로 시작하는 링크도 수집
elif (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
# company-review, jobs는 제외하지만 company-info/view는 포함
if ("/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가: {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
else:
print(f"[사람인] 링크 제외 (형식 불일치): {href_clean}")
except Exception as e:
print(f"[사람인] 링크 처리 오류: {e}")
pass
# 방법 2: "기업정보" 텍스트가 있는 링크 찾기 (전체 페이지에서) - 가장 중요!
# 다양한 XPath 시도 (company-info/view 링크 포함)
xpath_selectors = [
"//a[contains(text(), '기업정보')]",
"//a[text()='기업정보']",
"//button[contains(text(), '기업정보')]",
"//a[@title='기업정보']",
"//a[contains(@class, 'company_info')]",
"//a[contains(@class, 'btn_info')]",
"//a[contains(@class, 'company_popup')]",
"//a[contains(@href, '/zf_user/company-info/view')]",
"//a[contains(@href, '/zf_user/company/')]",
]
all_company_info_links = []
for xpath in xpath_selectors:
try:
found_links = driver.find_elements(By.XPATH, xpath)
print(f"[사람인] 방법2 ({xpath}): {len(found_links)}개 발견")
all_company_info_links.extend(found_links)
except Exception as e:
print(f"[사람인] 방법2 XPath 오류 ({xpath}): {e}")
pass
# 중복 제거
seen_elements = set()
unique_company_info_links = []
for link in all_company_info_links:
try:
elem_id = link.id
if elem_id not in seen_elements:
seen_elements.add(elem_id)
unique_company_info_links.append(link)
except:
unique_company_info_links.append(link)
print(f"[사람인] 방법2: 총 {len(unique_company_info_links)}개 '기업정보' 링크 발견 (중복 제거 후)")
for link in unique_company_info_links:
try:
href = link.get_attribute("href")
if not href:
# onclick 속성 확인
onclick = link.get_attribute("onclick")
if onclick and "/zf_user/company" in onclick:
url_match = re.search(r'/zf_user/company/[^\s\'"]+', onclick)
if url_match:
href = "https://www.saramin.co.kr" + url_match.group(0)
if href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
# 쿼리 파라미터는 유지
href_clean = href.split("#")[0].rstrip("/")
# /zf_user/company-info/view 링크 수집
if "/zf_user/company-info/view" in href_clean:
if href_clean not in links:
links.append(href_clean)
print(f"[사람인] 링크 추가 (기업정보 - company-info/view): {href_clean}")
# 정확히 /zf_user/company/로 시작하는 링크도 수집
elif (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
if ("/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가 (기업정보): {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
else:
print(f"[사람인] 링크 제외 (형식 불일치): {href_clean}")
except Exception as e:
print(f"[사람인] 방법2 링크 처리 오류: {e}")
pass
# 방법 3: 기업정보 버튼/링크 찾기 (다양한 선택자)
company_info_selectors = [
"a[href*='/zf_user/company']",
"a.company_info",
".company_info a",
"a[title*='기업정보']",
"a[aria-label*='기업정보']",
".btn_company_info",
".company_info_btn",
]
for selector in company_info_selectors:
try:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
for elem in elements:
href = elem.get_attribute("href")
if href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
href_clean = href.split("?")[0].split("#")[0].rstrip("/")
# 정확히 /zf_user/company/로 시작하는 링크만 수집
if (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
if ("/zf_user/company-info" not in href_clean and
"/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가 (선택자 {selector}): {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
except:
pass
# 방법 4: 각 채용 공고 항목에서 "기업정보" 버튼 찾기 (가장 중요!)
try:
# 사람인 검색 결과의 채용 공고 항목 찾기 (더 많은 선택자 시도)
job_item_selectors = [
".item_recruit",
".recruit_item",
".job_item",
".list_item",
"[class*='item_recruit']",
"[class*='recruit_item']",
"[class*='list_item']",
"div[class*='item']",
"li[class*='item']",
]
all_job_items = []
for selector in job_item_selectors:
try:
items = driver.find_elements(By.CSS_SELECTOR, selector)
all_job_items.extend(items)
except:
pass
# 중복 제거
seen_items = set()
unique_job_items = []
for item in all_job_items:
try:
item_id = item.id
if item_id not in seen_items:
seen_items.add(item_id)
unique_job_items.append(item)
except:
unique_job_items.append(item)
print(f"[사람인] 방법4: {len(unique_job_items)}개 채용 공고 항목 발견")
for idx, item in enumerate(unique_job_items):
try:
# 각 항목에서 "기업정보" 버튼/링크 찾기
# 방법 4-1: "기업정보" 텍스트가 있는 링크 찾기
company_info_buttons = item.find_elements(By.XPATH, ".//a[contains(text(), '기업정보')]")
# 방법 4-2: href에 /zf_user/company 또는 /zf_user/company-info/view가 있는 링크 찾기
if not company_info_buttons:
company_info_buttons = item.find_elements(By.CSS_SELECTOR, "a[href*='/zf_user/company'], a[href*='/zf_user/company-info/view']")
# 방법 4-2-1: btn_info 클래스가 있는 링크 찾기 (사용자가 제공한 HTML 구조)
if not company_info_buttons:
company_info_buttons = item.find_elements(By.CSS_SELECTOR, "a.btn_info, a.company_popup, .area_corp_info a")
# 방법 4-3: 버튼 클래스가 있는 링크 찾기
if not company_info_buttons:
company_info_buttons = item.find_elements(By.CSS_SELECTOR, "a.btn, button, .btn_company_info, .company_info_btn")
print(f"[사람인] 항목 {idx+1}: {len(company_info_buttons)}개 '기업정보' 버튼 발견")
for button in company_info_buttons:
try:
href = button.get_attribute("href")
if not href:
# onclick 속성에서 링크 추출 시도
onclick = button.get_attribute("onclick")
if onclick and "/zf_user/company" in onclick:
# onclick에서 URL 추출
import re
url_match = re.search(r'/zf_user/company/[^\s\'"]+', onclick)
if url_match:
href = "https://www.saramin.co.kr" + url_match.group(0)
if href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
# 쿼리 파라미터는 유지
href_clean = href.split("#")[0].rstrip("/")
# /zf_user/company-info/view 링크 수집
if "/zf_user/company-info/view" in href_clean:
if href_clean not in links:
links.append(href_clean)
print(f"[사람인] 링크 추가 (항목 {idx+1} '기업정보' 버튼 - company-info/view): {href_clean}")
# 정확히 /zf_user/company/로 시작하는 링크도 수집
elif (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
if ("/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가 (항목 {idx+1} '기업정보' 버튼): {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
else:
print(f"[사람인] 링크 제외 (형식 불일치): {href_clean}")
except Exception as e:
print(f"[사람인] 항목 {idx+1} 버튼 처리 오류: {e}")
pass
except Exception as e:
print(f"[사람인] 항목 {idx+1} 처리 오류: {e}")
pass
except Exception as e:
print(f"[사람인] 방법4 오류: {e}")
import traceback
print(traceback.format_exc())
pass
# 방법 5: 사람인 검색 결과의 실제 구조에 맞는 선택자 추가
try:
# 사람인 검색 결과 페이지의 실제 구조 확인
page_html = driver.page_source
if "/zf_user/company" in page_html:
# 더 구체적인 선택자로 시도 (채용 공고 링크 제외)
additional_selectors = [
"a[href*='/zf_user/company']:not([href*='/zf_user/jobs'])",
".item_recruit a[href*='/zf_user/company']",
".list_item a[href*='/zf_user/company']",
"[class*='item'] a[href*='/zf_user/company']",
]
for selector in additional_selectors:
try:
elements = driver.find_elements(By.CSS_SELECTOR, selector)
print(f"[사람인] 방법5 ({selector}): {len(elements)}개 요소 발견")
for elem in elements:
href = elem.get_attribute("href")
if href and "/zf_user/company" in href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
href_clean = href.split("?")[0].split("#")[0].rstrip("/")
# 정확히 /zf_user/company/로 시작하는 링크만 수집
if (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
if ("/zf_user/company-info" not in href_clean and
"/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가 (추가선택자 {selector}): {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
else:
print(f"[사람인] 링크 제외 (형식 불일치): {href_clean}")
except Exception as e:
print(f"[사람인] 방법5 선택자 오류 ({selector}): {e}")
pass
except Exception as e:
print(f"[사람인] 방법5 오류: {e}")
pass
# 방법 6: 사람인 검색 결과에서 회사명 클릭 영역 찾기
try:
# 각 채용 공고 항목에서 회사명 영역 찾기
recruit_items = driver.find_elements(By.CSS_SELECTOR, ".item_recruit, .list_item, [class*='item_recruit'], [class*='list_item']")
print(f"[사람인] 방법6: {len(recruit_items)}개 채용 공고 항목 발견")
for item in recruit_items:
try:
# 회사명 영역에서 회사 상세 페이지 링크 찾기
# 회사명은 보통 h2, h3, strong, a 태그에 있음
company_name_elements = item.find_elements(By.CSS_SELECTOR, "h2 a, h3 a, strong a, .company_name a, a.company_name")
for elem in company_name_elements:
href = elem.get_attribute("href")
if href and "/zf_user/company" in href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
href_clean = href.split("?")[0].split("#")[0].rstrip("/")
# 정확히 /zf_user/company/로 시작하는 링크만 수집
if (href_clean.startswith("https://www.saramin.co.kr/zf_user/company/") or
href_clean.startswith("/zf_user/company/")):
if ("/zf_user/company-info" not in href_clean and
"/zf_user/company-review" not in href_clean and
"/zf_user/jobs" not in href_clean and
"/zf_user/company/" in href_clean and
href_clean not in links):
links.append(href_clean)
print(f"[사람인] 링크 추가 (회사명 영역): {href_clean}")
else:
print(f"[사람인] 링크 제외 (잘못된 경로): {href_clean}")
else:
print(f"[사람인] 링크 제외 (형식 불일치): {href_clean}")
except Exception as e:
print(f"[사람인] 방법6 항목 처리 오류: {e}")
pass
except Exception as e:
print(f"[사람인] 방법6 오류: {e}")
pass
except Exception as e:
print(f"[사람인] 링크 추출 오류: {e}")
print(f"[사람인] 페이지 {current_page}에서 {len(links) - page_links_count}개 링크 발견 (총 {len(links)}개)")
# 목표 개수에 도달했거나, 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if max_urls > 0 and len(links) >= max_urls:
break
# 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if current_page > pages and len(links) == page_links_count:
break
try:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
except:
pass
current_page += 1
except Exception as e:
print(f"[사람인] 크롤링 오류: {e}")
print(f"[사람인] 총 {len(links)}개 회사 링크 수집 완료")
return list(set(links))
def get_jobkorea_company_links(driver, keyword, pages=10, max_urls=0):
"""잡코리아 사이트에서 회사 검색하여 회사 상세 페이지 링크 수집 (목표 개수에 도달할 때까지 페이지 확장)"""
links = []
current_page = 1
max_pages = pages * 3 # 최대 3배까지 확장 가능
try:
while current_page <= max_pages:
url = f"https://www.jobkorea.co.kr/Search/?stext={quote_plus(keyword)}&tabType=recruit&Page_No={current_page}"
driver.get(url)
time.sleep(2)
page_links_count = len(links)
# 잡코리아 검색 결과에서 회사 상세 페이지 링크 찾기
selectors = [
"a[href*='/company']", # 회사 상세 페이지 링크
"a.company_name",
".company_name a",
"div.company_name a",
"a[href*='company_view']",
"a[href*='Company']",
]
for selector in selectors:
try:
results = driver.find_elements(By.CSS_SELECTOR, selector)
for res in results:
href = res.get_attribute("href")
if href and ("jobkorea.co.kr" in href or href.startswith("/")):
# 상대 경로를 절대 경로로 변환
if href.startswith("/"):
href = "https://www.jobkorea.co.kr" + href
if "company" in href.lower() and href not in links:
links.append(href)
except:
pass
# 목표 개수에 도달했으면 중단
if max_urls > 0 and len(links) >= max_urls:
break
# 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if current_page > pages and len(links) == page_links_count:
break
# 다음 페이지 체크
try:
next_button = driver.find_element(By.CSS_SELECTOR, ".paging a.next, .paging .next")
if "disabled" in next_button.get_attribute("class") or not next_button.is_enabled():
if current_page > pages: # 기본 페이지 범위를 넘었으면 중단
break
except:
if current_page > pages: # 기본 페이지 범위를 넘었으면 중단
break
current_page += 1
except Exception as e:
pass
return list(set(links))
def get_albamon_company_links(driver, keyword, pages=10, max_urls=0):
"""알바몬 사이트에서 회사 검색하여 회사 상세 페이지 링크 수집 (목표 개수에 도달할 때까지 페이지 확장)"""
links = []
current_page = 1
max_pages = pages * 3 # 최대 3배까지 확장 가능
try:
while current_page <= max_pages:
url = f"https://www.albamon.com/list/gi/mon_list.asp?keyword={quote_plus(keyword)}&page={current_page}"
driver.get(url)
time.sleep(2)
page_links_count = len(links)
# 알바몬 검색 결과에서 회사 상세 페이지 링크 찾기
selectors = [
"a[href*='company']", # 회사 상세 페이지 링크
"a.company_name",
".company_name a",
"div.company_name a",
"a[href*='gi_view']",
]
for selector in selectors:
try:
results = driver.find_elements(By.CSS_SELECTOR, selector)
for res in results:
href = res.get_attribute("href")
if href and ("albamon.com" in href or href.startswith("/")):
# 상대 경로를 절대 경로로 변환
if href.startswith("/"):
href = "https://www.albamon.com" + href
if ("company" in href.lower() or "gi_view" in href.lower()) and href not in links:
links.append(href)
except:
pass
# 목표 개수에 도달했으면 중단
if max_urls > 0 and len(links) >= max_urls:
break
# 기본 페이지 범위를 넘었는데 새 링크가 없으면 중단
if current_page > pages and len(links) == page_links_count:
break
# 다음 페이지 체크
try:
next_button = driver.find_element(By.CSS_SELECTOR, ".paging a.next, .paging .next")
if "disabled" in next_button.get_attribute("class") or not next_button.is_enabled():
if current_page > pages: # 기본 페이지 범위를 넘었으면 중단
break
except:
if current_page > pages: # 기본 페이지 범위를 넘었으면 중단
break
current_page += 1
except Exception as e:
pass
return list(set(links))
def extract_company_info(driver, url):
info = {
"URL": url,
"사이트명": "",
"회사명": "",
"대표자명": "",
"회사주소": "",
"이메일": ""
}
try:
driver.set_page_load_timeout(10)
driver.get(url)
time.sleep(1.5)
info["사이트명"] = driver.title.strip() if driver.title else ""
body_text = driver.find_element(By.TAG_NAME, "body").text
# 채용 사이트별 특별 처리
url_lower = url.lower()
# 사람인 (saramin.co.kr) - 회사 상세 페이지 또는 company-info/view 페이지인 경우
if "saramin.co.kr" in url_lower and ("/zf_user/company" in url_lower or "/zf_user/company-info/view" in url_lower):
print(f"[사람인 상세페이지] 접근 중: {url}")
try:
# /zf_user/company-info/view 페이지인 경우, 회사 상세 페이지로 이동하는 링크 찾기
if "/zf_user/company-info/view" in url_lower:
print(f"[사람인] company-info/view 페이지에서 회사 상세 페이지 링크 찾기...")
time.sleep(2)
# 회사 상세 페이지로 가는 링크 찾기
company_detail_links = driver.find_elements(By.CSS_SELECTOR, "a[href*='/zf_user/company/']")
for link in company_detail_links:
try:
href = link.get_attribute("href")
if href and "/zf_user/company/" in href and "/zf_user/company-info" not in href:
if href.startswith("/"):
href = "https://www.saramin.co.kr" + href
print(f"[사람인] 회사 상세 페이지로 이동: {href}")
driver.get(href)
time.sleep(2)
break
except:
pass
# 페이지가 완전히 로드될 때까지 대기
time.sleep(2)
print(f"[사람인 상세페이지] 페이지 제목: {driver.title}")
# 회사명 추출 (사람인 구조) - 더 많은 선택자 시도
company_selectors = [
"h1.company_name",
"div.company_name",
".company_name",
"h2.company_name",
"span.company_name",
"strong.company_name",
".company_info h1",
".company_info .company_name",
".company_header h1",
".company_header .company_name",
"h1[class*='company']",
".item_company h1",
".item_company .company_name",
"div[class*='company_name']",
# 페이지 제목에서 회사명 추출 시도
]
for selector in company_selectors:
try:
elem = driver.find_element(By.CSS_SELECTOR, selector)
company_text = elem.text.strip()
# 이상한 텍스트 필터링 (너무 짧거나 일반적인 문구 제외)
if company_text and len(company_text) > 2 and not any(x in company_text for x in ['에 대해', '많은 사람', '궁금해', '검색', '사람인']):
info["회사명"] = company_text
print(f"[사람인] 회사명 추출 성공 (선택자: {selector}): {company_text}")
break
except:
pass
# 선택자로 못 찾았으면 페이지 제목에서 추출 시도
if not info["회사명"]:
try:
page_title = driver.title.strip()
# 제목에서 회사명 추출 (예: "회사명 | 사람인" 형식)
if "|" in page_title:
company_name = page_title.split("|")[0].strip()
if company_name and len(company_name) > 2:
info["회사명"] = company_name
print(f"[사람인] 회사명 추출 성공 (제목): {company_name}")
except:
pass
# 홈페이지 URL 추출 (기업정보 섹션에서)
homepage_url = None
print(f"[사람인 상세페이지] 홈페이지 URL 추출 시작...")
# 방법 1: dt/dd 구조에서 찾기 (가장 정확)
try:
# "홈페이지" 텍스트가 있는 dt 요소 찾기
dt_elements = driver.find_elements(By.XPATH, "//dt[contains(text(), '홈페이지')]")
print(f"[사람인 상세페이지] 방법1: dt 요소 {len(dt_elements)}개 발견")
for dt in dt_elements:
try:
# 다음 형제 dd 요소 찾기
dd = dt.find_element(By.XPATH, "./following-sibling::dd[1]")
# dd 안의 링크 찾기
link = dd.find_element(By.CSS_SELECTOR, "a[href^='http']")
homepage_url = link.get_attribute("href")
if homepage_url:
print(f"[사람인 상세페이지] 방법1 성공: {homepage_url}")
break
except:
try:
# dd 안에 직접 텍스트로 URL이 있을 수도 있음
dd = dt.find_element(By.XPATH, "./following-sibling::dd[1]")
dd_text = dd.text.strip()
if dd_text.startswith("http"):
homepage_url = dd_text.split()[0] # 첫 번째 단어가 URL일 가능성
print(f"[사람인 상세페이지] 방법1 성공 (텍스트): {homepage_url}")
break
except: