본문 바로가기
Python/Web Scraping

[Project] Python Jobs - Web Scraping (#코딩공부)

by 함께 공부해요 2020. 3. 4.

https://github.com/wook2124/Web_Scraping

 

wook2124/Web_Scraping

Physical Therapy Jos / Python Jobs. Contribute to wook2124/Web_Scraping development by creating an account on GitHub.

github.com


<복습>

https://wook-2124.tistory.com/53

 

[Project] Physical Therapy Jobs - Web Scraping (#코딩공부)

https://github.com/wook2124/Web_Scraping wook2124/Web_Scraping Physical Therapy Jos / Python Jobs. Contribute to wook2124/Web_Scraping development by creating an account on GitHub. github.com <복습>..

wook-2124.tistory.com

 

<준비물>

https://repl.it/

 

Online IDE, Editor, and Compiler - Fast, Powerful, Free

Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin (beta), QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeS

repl.it

 

<코드기록>

 

# https://kr.indeed.com/jobs?q=python&limit=50&radius=25&start=50
# main.py
from py_indeed import get_jobs as get_indeed_jobs
from save import save_file

indeed_jobs = get_indeed_jobs()

jobs = indeed_jobs 
save_file(jobs)


# py_indeed.py
import requests
from bs4 import BeautifulSoup

LIMIT = 50
URL = f"https://kr.indeed.com/jobs?q=python&limit={LIMIT}"

def get_last_page():
    result = requests.get(URL)
    soup = BeautifulSoup(result.text, "html.parser")
    pagination = soup.find("div", {"class": "pagination"})

    links = pagination.find_all('a')
    pages = []
    for link in links[:-1]:
        pages.append(int(link.string))

    max_page = pages[-1]
    return max_page

def extract_job(html):
    title = html.find("div", {"class": "title"}).find("a")["title"]
    company = html.find("span", {"class": "company"})
    if company is not None:
      company = str(company.string)
      company = company.strip()
    else:
      company = None  
    location = html.find("div", {"class": "recJobLoc"})["data-rc-loc"]
    job_id = html["data-jk"]
    salary = html.find("span", {"class": "salaryText"})
    if salary is not None:
      salary = str(salary.string)
    else:
      salary = None
    return {
        'title': title,
        'company': company,
        'location': location,
        "link": f"https://www.indeed.com/viewjob?jk={job_id}",
        'salary': salary
    }

def extract_jobs(last_page):
  jobs = []
  for page in range(last_page):
    print(f"Scrapping Indeed: Page: {page}")
    result = requests.get(f"{URL}start={page * LIMIT}")
    soup = BeautifulSoup(result.text, "html.parser")
    results = soup.find_all("div", {"class": "jobsearch-SerpJobCard"})
    for result in results:
      job = extract_job(result)
      jobs.append(job)
  return jobs

def get_jobs():
  last_page = get_last_page()
  jobs = extract_jobs(last_page)
  return jobs
 

# save.py
import csv

def save_file(jobs):
  file = open("jobs.csv", mode="w")
  writer = csv.writer(file)
  writer.writerow(["title", "company", "location", "link", "salary"])
  for job in jobs:
    writer.writerow(list(job.values()))
  return

# jobs에 있는 각 job을 가지고 row(행)를 작성함
# job이 가진 값의 list를 row(행)로 가져올 것임

1. URL 수정하기

Physical Therapy Jobs와 마찬가지 Web Scraping 하면서 만들어둔 indeed.py를 import한다음, 하고자하는 Python Jobs URL링크로 바꿨다.

 

URL은 limit=까지 복붙하고 그 뒤에는 50개의 radius로 검색한 것을 알 수 있다.


2. title, company 가져오기

div class="title"과 span class="company"를 동시에 확인했다.

 

company만 None값으로 company를 입력해두지 않은 예외조건을 if문으로 분별해줬다.

 

만약(if) company가 None값이 아니라 company 값을 가지고 있으면 str(문자열)로 바꾼뒤, strip으로 빈칸을 없앴다.

그렇지 않고(else) None값으로 company 값이 없다면, 그냥 바로 None 값으로 나타내게끔 했다.


3. location, link 가져오기

location은 div class="recJobLoc"[data-rc-loc]이고, link는 div class data-jk의 값이다.

 

link인 data-jk의 값이 Python Job URL link와 동일한 것을 알 수 있다.

 

locationdiv class="recJobLoc"[data-rc-loc]link div class data-jk를 각각 적어주자.


4. salary 추출하기

span class="salaryText"Physical Therapy Jobs에서 추출할 때와 동일한 것을 알 수 있다.

 

salary 역시 급여가 적혀있지 않는 기업공고들도 있어서 if문으로 걸러줬다.


5. 마무리 하기

Next(다음) 전까지 1~8 page를 가져오면 된다.

 

main.py에서 py_indeed로 from을 바꿔주고 실행하면 0~7 page가 출력이 된다.

기계는 0부터 세니까, 결론적으로 1~8 page 추출 성공!

 

csv파일로도 잘 옮겨졌고, 이제 Google Spreadsheet로 옮기면 끝!

 

https://wook-2124.tistory.com/45?category=890509

 

[Python] #2.15 Saving to CSV(Comma-separated values) / #2.16 OMG THIS IS AWESOME (#코딩공부)

https://youtu.be/1tGVS0LO2Do <복습> https://wook-2124.tistory.com/44 [Python] #2.14 What is CSV(Comma-separated values) (#코딩공부) https://youtu.be/t2-yu7e7lFM <복습> https://wook-2124.tistory.com/..

wook-2124.tistory.com

위에 정리했던 방법대로 옮겨주면,

 

그러나 Physical Therapy Jobs Web Scraping과 다르게 반복되서 추출이 됐다.

 

이 문제에 대해서는 나중에 꼭 다시 살펴보도록 하고, 이것으로 Web Scraping Project 끝!!

Python Jobs(Web Scraping).xlsx
0.01MB


※ 신종 코로나 바이러스 조심하세요!!!!

댓글