링크드인에서 채용공고 크롤링하기
'사람인', '프로그래머스', '그림닷컴' 등에서 크롤링 하는건 쉬웠는데 여기는 힘들었다.
우선 데이터를 가져오는거 까진 평소처럼 했는데 항상 250개나 500개쯤에서 아이디가 벤을 먹었다....
그래서 그 이후는 계속 error가 출력되는데 조금 무서웠다.ㅋㅋ
내 이메일계정 3개를 바치고 지인도 가입시켜서 그 아이디도 벤먹으면서 겨우 완성했다..ㅎ
보통 하루뒤에 벤이 풀리던데 내 계정 하나는 여러번 벤먹어서 그런가 지금 정리하면서 다시 코드를 실행했는데 아직도 벤이당ㅎㅎ.
그래도 코드를 완성해서 겨우 캡스톤 발표까지 할 수 있었달까~
진짜 3~4일 걸린거같다.
[링크드인 홈페이지]
링크드인: https://www.linkedin.com
크롤링 방법
왼쪽 화면에서는
이렇게 40개정도 나오기때문에 url을 넘겨서 해당 내용들을 가져오도록 했다.
크롤링 순서
1, 모듈 불러오기
동적 페이지이기 때문에 bs가 아닌 selenium을 사용
csv파일로 저장하기 위한 모듈도 import
2. 크롬드라이버로 로그인하기
참고로
이와같이 크롬드라이버 버젼 오류가 난다면 크롬드라이버를 현재 크롬버젼에 맞게 바꿔주면 된다.
현재에러 - 크롬드라이버 버전: 100 내 크롬버전: 102
그래서 크롬드라이버를 102로 교체해주면 해결된다.
크롬드라이버 설치경로: https://chromedriver.chromium.org/downloads
3. 검색페이지의 라벨링 값 넣은 주소에서 나온 채용공고의 id값 찾아서 저장하기
driver.find_elements_by_css_selector()와 같은 함수를 이용해 이동
.get_attribute : 옵션 값을 text로 얻기위한 함수
이렇게 얻은 id값을 code.csv라는 파일로 저장함(이후 채용공고를 크롤링할때 또 돌리지 않도록)
<꿀팁>
검사에 들어가서 마우스 우클릭 -> 복사 -> 요소 복사
이렇게 하면 자동으로 위치를 따올 수 있다.
[id찾기 크롤링 실행화면]
왼쪽은 구글드라이버가 실행되는 화면
4. 채용공고id값을 넣은 url에서 채용공고 text 크롤링하기
이번엔 xpath를 가져왔다.
.text로 해당 html의 text만을 가져와서 저장
code_data.csv로 데이터를 저장하였다.
html을 로딩하는데 시간이 걸리기 때문에 time.sleep()함수와 driver.implicity_wait()를 꼭 사용하자.
[소스코드]
from ast import excepthandler
from operator import index
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv
import time
import pandas as pd
# https://www.linkedin.com/jobs/search/?currentJobId=10000&geoId=103644278&keywords=database&location=%EB%AF%B8%EA%B5%AD
import chromedriver_autoinstaller as chromedriver
chromedriver.install()
driver = webdriver.Chrome('chromedriver') # https://chromedriver.chromium.org/downloads
driver.implicitly_wait(10)
# 로그인 페이지로 이동
URL = 'https://www.linkedin.com/login/ko?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin'
driver.get(url=URL)
driver.implicitly_wait(5)
# 3091327134 3084008208 3092650694 3083077458 3089270328 3090144106 3089661302 3072802817 3083678124 3083640103
# 로그인
driver.find_element_by_id('username').send_keys('ajfoddl123@naver.com') # ID 입력
driver.find_element_by_id('password').send_keys('!thstjdgh1256') # PW 입력
search_btn = driver.find_element_by_css_selector('#organic-div > form > div.login__form_action_container > button') # button element
search_btn.click()
# print('login done!!!!!!!!!!!!!!!!!!!')
hashtag = ['backend%20developer','software','system','database','network','Frontend%20Developer','Application','Service','Game%20Developer','AI%20Engineer']
baseUrl = 'https://www.linkedin.com/jobs/search/?currentJobId='
midUrl = '&geoId=103644278&keywords='
tailUrl = '&location=%EB%AF%B8%EA%B5%AD' # 0~975 그 이상도 가능
url1 = 'https://www.linkedin.com/jobs/search/?geoId=103644278&keywords='
url2 = '&location=미국&start='
# 크롤링 url 탐색
code_lists = []
for h in hashtag[7:]:
code_list = []
for i in range(0,975,25): #975
URL = url1 + h + url2 + str(i)
print(URL)
driver.get(url=URL)
driver.implicitly_wait(10)
try:
for item in driver.find_elements_by_css_selector("body > div.application-outlet > div.authentication-outlet > div.job-search-ext > div.jobs-search-two-pane__wrapper > div > section.jobs-search__left-rail > div > div > ul > li"):
code = item.get_attribute('data-occludable-job-id')
print(code)
code_list.append(code)
data = {
'code' : code,
'hashtag' : h
}
with open('./code.csv', 'a', encoding='utf-8', newline='') as csvfile:
fieldnames = ['code', 'hashtag']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writerow(data)
except:
print('error2')
continue
code_lists.append(code_list)
print('찾은 코드 컬럼수:', len(code_lists))
print('컴럼 하나당 코드수:', len(code_lists[0]))
df = pd.read_csv('code.csv', encoding='utf-8')
df = pd.DataFrame(df)
df.dropna()
# 크롤링 시작
cnt = 1
for h in hashtag[:2]:
for i in range(len(df)):
try:
c = df.loc[i, "code"]
c = int(c)
h = df.loc[i, 'hash']
try:
# Search Keyword
URL = baseUrl + str(c) + midUrl + h + tailUrl
print(URL, end='\n')
driver.get(url=URL)
driver.implicitly_wait(10)
item = driver.find_elements_by_xpath("//*[@id='main']/div/section[2]/div/div[2]/div[1]/div/div[2]")
content = item[0].text
print(content)
rinkedin_data = {
'content' : content,
'tag' : h
}
with open('./code_data.csv', 'a', encoding='utf-8', newline='') as csvfile:
fieldnames = ['content', 'tag']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writerow(rinkedin_data)
print(cnt, "번째 성공")
cnt +=1
time.sleep(3)
except:
print("error1!!")
continue
except:
print("error2!!")
continue
print('crwaling clear!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
# print('총데이터: ',cnt,'개')
driver.close()
[결과]
code_data.csv - vscode
code_data.csv - 구글코랩
총 '7420개의 데이터'가 크롤링 되었음을 확인하였다.
code.csv - vscode
[부가]
차단된 내 구글계정ㅎㅎ..
우선 난 링크드인은 사용 못할듯..
코드를 짜고보니 너무 느렸고 생각보다 길이가 길어졌다.
보다 효율적으로 짜는 방법이 있을것같고 왜 이번 코드에서는 벤을 안먹었는지가 궁금하다.
// 이제 이것으로 캡스톤에서 사용한 bert와 k-means clustering을 사용했던 내용을 포스팅할 예정이다.
이후에 캡스톤 통합본도 프로젝트에 포스팅하자.
'Web > 크롤링' 카테고리의 다른 글
[Selenium] 사람인(Saramin) 채용공고 크롤링 (2) | 2022.06.29 |
---|---|
[Selenium] 프로그래머스(Programmers) 채용공고 크롤링 (0) | 2022.06.29 |
[BeautifulSoup] 사이트에서 이미지 크롤링 (0) | 2022.05.22 |
댓글