웹스크래핑 기본 절차
code
웹 스크래핑의 절차는 3단계
code
main.py
from indeed import get_jobs as get_indeed_jobs
from so import get_jobs as get_so_jobs
from save import save_to_file
#필요한 펑션들을 불러오는 작업들.
so_jobs =get_so_jobs()
indeed_jobs = get_indeed_jobs()
jobs = so_jobs + indeed_jobs
save_to_file(jobs)
Indeed.py(인디드닷컴에서 파이썬 개발자 공고 추출)
from bs4 import BeautifulSoup
# html에서 정보를 추출하기위한 모듈
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/ 공식문서.
LIMIT = 50
URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}"
def get_last_page():
result = requests.get(URL)
# indeed사이트에서 python 검색하는 url입력
soup = BeautifulSoup(result.text, "html.parser")
# html코드 파싱
pagination = soup.find("div", {"class": "pagination"})
# inspect로 find html with numbers in the pages
links = pagination.find_all('a')
pages = []
for link in links[:-1]:
pages.append(int(link.string))
#Append pages in the list as finding the number of the pages
max_page = pages[-1]
return max_page
def extract_job(html):
title = html.find("h2", {"class": "title"}).find("a")["title"]
# Code has been changed from div to h2
company = html.find("span", {"class": "company"})
# print(company)
if company:
company_anchor = company.find('a')
if company_anchor is not None:
company = str(company_anchor.string)
#If there is a existing company link, print the string of the anchor
else:
company = str(company.string)
# If not, print the string of the span
company = company.strip()
else:
company = None
location = html.find("div", {"class": "recJobLoc"})["data-rc-loc"]
# print(location)
# 각 업무를 누르면 회사모집 페이지로 들어가짐
# 누르면 URL이 이동되고 연결되는 id가 URL에 표시된다
# id넘버까지 남겨두고 쓸모없는 것을 지우고 다시 확인했을때
# 정상출력이된다면 그 id넘버를 html에서 찾는다
job_id = html['data-jk']
# extract_indeed_jobs에 있는 변수 results에서
# 아까 확인했던 URL의 id를 찾을수 있는 것은 data-jk이다
return {'title': title,
'company': company,
'location': location,
'link': f'https://www.indeed.com/viewjob?jk={job_id}'}
# 회사업무와 회사명칭, 주소, 회사모집페이지 리턴
# As pages goes to the next, url changes
# First page url: https://www.indeed.com/jobs?q=python&limit=50
# Lasg page url: https://www.indeed.com/jobs?q=python&limit=50&start=950
# 각 페이지 일자리정보 추출 리스트에 담고 모든일자리를 반환
def extract_jobs(last_page):
jobs = []
for page in range(last_page):
print(f"Scrapping indeed page {page}")
# 총20페이지 페이지 전부 반복하는지 확인작업
result = requests.get(f'{URL}&start={page*LIMIT}')
# 페이지 요청
# print(result.status_code)
# 정상적으로 요청되는지 확인 200이 20번 나오면 성공
soup = BeautifulSoup(result.text, 'html.parser')
results = soup.find_all('div', {'class': 'jobsearch-SerpJobCard'})
# F12눌러서 페이지의 일자리 링크 html찾기
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
# This function's name has been changed
# after it has been put in indded.py
so.py
import requests
from bs4 import BeautifulSoup
# html에서 정보를 추출하기위한 모듈
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/ 공식문서.
URL = f"https://stackoverflow.com/jobs?q=python&sort=3&pg=i"
def get_last_page():
result = requests.get(URL)
# Stackoverflow사이트에서 python 검색하는 url입력
soup = BeautifulSoup(result.text, "html.parser")
# html코드 파싱
pages = soup.find("div", {"class": "s-pagination"}).find_all("a")
# inspect로 find html with numbers in the pages
last_page = pages[-2].get_text(strip=True)
return int(last_page)
def extract_job(html):
title = html.find("h2",{"class":"fs-body3"}).find("a")["title"]
company, location = html.find("h3", {"class":"fs-body1"}).find_all("span", recursive=False)
location = company.get_text(strip=True).strip("-").strip("\r").strip("\n")
company = company.get_text(strip=True)
job_id = html["data-jobid"]
return {"title" : title, "company" : company, "location" : location, "apply_Link" : f"https://stackoverflow.com/jobs/{job_id}"}
def extract_jobs(last_page):
jobs = []
for page in range(last_page):
print(f"Scrapping SO page {page}")
result = requests.get(f"{URL}&pg= {page+1}")
soup = BeautifulSoup(result.text , "html.parser")
results = soup.find_all("div", {"class" : "-job"})
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_to_file(jobs):
file = open("jobs.csv", mode="w")
#jobs.csv 를 열고, 라이터모드 on.
writer = csv.writer(file)
writer.writerow(["title", "company", "location", "link"])
#writer는 csv를 작성하는 라이터를 의미, 그리고 ""4가지 row를 작성.
for job in jobs:
writer.writerow(list(job.values()))
return
#jobs에 잡들값을, 리스트로 변환후 입력, 리턴.
그리고, 나온 jobs.csv 를 스프레드시트에 업로드하면 완성!
Google Sheets - create and edit spreadsheets online, for free.