5.16 Pages part Two
이전 게시물에서 검색 첫 페이지에 div ( 페이지 개수를 세주는 div ) 가 없을 때
검색 결과에 구인정보가 있는지 없는지 출력해주는 코드를 작성했었다.
보통 구인 정보가 있는 경우에는 스크래핑 할 페이지가 1개 만 있다는것을 의미한다.
만약 페이지를 받게 된다면, 몇 개가 있는지 세어봐야 한다.
만약 5개 페이지 밖에 없으면 5개의 div 를 받게 된다.
만약 5개 보다 더 많은 경우에도 5개까지만 나타내는 코드를 작성한다. ( 웹사이트 부하 방지 )
만약 5개보다 적게 있다면, count 를 그대로 return 해준다.
< div 개수로 페이지 count 하는 코드 >
from requests import get
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_page_count(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
pagination = soup.find('nav', attrs={'aria-label':'pagination'})
pages = pagination.find_all('div', recursive=False)
count = len(pages)
if count >= 5:
return 5
else:
return count
while(True):
pass
print(get_page_count('python'))
print(get_page_count('nextjs'))
print(get_page_count('django'))
print(get_page_count('nestjs'))
def extract_indeed_jobs(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
job_list = soup.find('ul', class_='jobsearch-ResultsList')
jobs = job_list.find_all('li', recursive=False)
for job in jobs:
zone = job.find('div', class_='mosaic-zone')
if zone == None:
anchor = job.select_one('h2 a')
title = anchor['aria-label']
link = anchor['href']
company = job.find('span',class_='companyName')
location = job.find('div',class_='companyLocation')
job_data = {
'link':f'https://kr.indeed.com{link}',
'company': company.string,
'location': location.string,
'position': title
}
results.append(job_data)
for result in results:
print(result,'\n////////\n')
while(True):
pass
출력값:
python 과 django 는 구인정보가 많아 5페이지 이상은 출력되며,
nest js 와 next js 는 구인정보가 적어 1페이지 정도가 출력되는거 같다.
(1페이지만 출력 시 페이지 개수 세주는 div 가 없어 0 으로 출력됨 )
< 구인 정보 개수도 세주는 코드 >
from requests import get
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_page_count(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
search_count = soup.find('div',class_='jobsearch-JobCountAndSortPane-jobCount')
if search_count == None:
print('검색 결과 없음')
else:
search_count2 = search_count.find('span')
print(search_count2.string)
pagination = soup.find('nav', attrs={'aria-label':'pagination'})
pages = pagination.find_all('div', recursive=False)
count = len(pages)
if count >= 5:
return 5
else:
return count
while(True):
pass
print(get_page_count('pyhon'))
print(get_page_count('nextjs'))
print(get_page_count('django'))
print(get_page_count('nestjs'))
def extract_indeed_jobs(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
job_list = soup.find('ul', class_='jobsearch-ResultsList')
jobs = job_list.find_all('li', recursive=False)
for job in jobs:
zone = job.find('div', class_='mosaic-zone')
if zone == None:
anchor = job.select_one('h2 a')
title = anchor['aria-label']
link = anchor['href']
company = job.find('span',class_='companyName')
location = job.find('div',class_='companyLocation')
job_data = {
'link':f'https://kr.indeed.com{link}',
'company': company.string,
'location': location.string,
'position': title
}
results.append(job_data)
for result in results:
print(result,'\n////////\n')
while(True):
pass
출력값:
안에 keyword를 예를 들어 python 으로 입력하는데,
스크래핑 할 페이지 개수도 같이 써준다.
그러면 코드가 python 키워드로 페이지 개수를 알아내 pages 로 받는다.
< 스크래핑 할 페이지 개수와 구인 정보 개수를 출력해주는 코드 >
from requests import get
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_page_count(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
search_count = soup.find('div',class_='jobsearch-JobCountAndSortPane-jobCount')
if search_count == None:
print('검색 결과 없음')
else:
search_count2 = search_count.find('span')
print(search_count2.string)
pagination = soup.find('nav', attrs={'aria-label':'pagination'})
pages = pagination.find_all('div', recursive=False)
count = len(pages)
if count >= 5:
return 5
elif count == 0:
return count+1
else:
return count
while(True):
pass
print(get_page_count('tyhon'))
print(get_page_count('모의해킹'))
print(get_page_count('django'))
print(get_page_count('penetration'))
def extract_indeed_jobs(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
job_list = soup.find('ul', class_='jobsearch-ResultsList')
jobs = job_list.find_all('li', recursive=False)
for job in jobs:
zone = job.find('div', class_='mosaic-zone')
if zone == None:
anchor = job.select_one('h2 a')
title = anchor['aria-label']
link = anchor['href']
company = job.find('span',class_='companyName')
location = job.find('div',class_='companyLocation')
job_data = {
'link':f'https://kr.indeed.com{link}',
'company': company.string,
'location': location.string,
'position': title
}
results.append(job_data)
for result in results:
print(result,'\n////////\n')
while(True):
pass
출력값:
이번에는 코드를 바꿔서 1페이지 출력해도 1로 출력하게 바꿨다.
count = len(pages)
if count >= 5:
return 5
elif count == 0:
return count+1
else:
return count
하지만 여전히 div 개수를 세는 코드로 인해 실제 스크랩할 페이지와 결과값은 다르다.
(div 전체 개수 = 페이지 div + 화살표 div 이기 때문에 실제 페이지 보다 +1 된다. )
pagination = soup.find('nav', attrs={'aria-label':'pagination'})
pages = pagination.find_all('div', recursive=False)
< 이전페이지, 다음페이지 등 화살표 div 를 제외해주고 출력하는 코드 >
from requests import get
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_page_count(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
search_count = soup.find('div',class_='jobsearch-JobCountAndSortPane-jobCount')
if search_count == None:
print('검색 결과 없음')
else:
search_count2 = search_count.find('span')
print(search_count2.string)
pagination = soup.find('nav',{'aria-label':'pagination'})
pages = pagination.select('div a')
count = len(pages)+1
for page in pages:
if page['aria-label'] == "Previous Page":
count -= 1
if page['aria-label'] == "Next Page":
count -= 1
if count >= 5:
return 5
else:
return count
while(True):
pass
print(get_page_count('nest'))
print(get_page_count('모의해킹'))
print(get_page_count('python'))
print(get_page_count('tyhon'))
def extract_indeed_jobs(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
job_list = soup.find('ul', class_='jobsearch-ResultsList')
jobs = job_list.find_all('li', recursive=False)
for job in jobs:
zone = job.find('div', class_='mosaic-zone')
if zone == None:
anchor = job.select_one('h2 a')
title = anchor['aria-label']
link = anchor['href']
company = job.find('span',class_='companyName')
location = job.find('div',class_='companyLocation')
job_data = {
'link':f'https://kr.indeed.com{link}',
'company': company.string,
'location': location.string,
'position': title
}
results.append(job_data)
for result in results:
print(result,'\n////////\n')
while(True):
pass
출력값:
< 다른 사용자의 코드가 있어 사용해본다. >
pagination = soup.find('nav',{'aria-label':'pagination'})
pages = pagination.select('div a')
count = len(pages)+1 # 현재 페이지에는 a 태그가 없어서 개수를 1개 추가해준다.
for page in pages:
if page['aria-label'] == "Previous Page":
count -= 1 # 이전 페이지가 존재한다면 a 태그를 빼준다.
if page['aria-label'] == "Next Page":
count -= 1 # 다음 페이지가 존재한다면 a 태그를 빼준다.
if count >= 5:
return 5
else:
return count
pages = pagination.select('div a')
→ div 를 선택한 다음, 안으로 들어가서 a를 가져와라, 그리고 pages 변수에 저장.
count = len(pages)+1
→ a 태그가 있는 pages 변수('nav'의 aria-label = 'pagination' 안에 있는 div)의 개수를 세어서 count 변수에 저장.
현재 페이지는 3 페이지, pagination-page-current 라고 표시된다.
현재 보고 있는 페이지(3 페이지)는 a 태그가 없다.
나머지 1,2,4,5 페이지의 div 에는 a태그가 존재하며,
추가로 이전페이지, 다음페이지 (화살표 div) 에도 a 태그가 존재한다.
현재 페이지에는 a 태그가 없기 때문에 a 태그 개수를 추가해주며,
그러므로 이전페이지, 다음페이지가 있으면 (화살표 div) a 태그 개수를 빼준다. ( 필요없기 때문 )
for page in pages:
if page['aria-label'] == "Previous Page":
count -= 1
if page['aria-label'] == "Next Page":
count -= 1
pages 변수를 page 로 반복한다.
만약 page안에 aria-label 이라는 key가 Previous Page 와 동일하다면 ( 이전 페이지 )
count = count -1
만약 page안에 aria-label 이라는 key가 Next Page 와 동일하다면 ( 다음 페이지 )
count = count -1
페이지 개수에 따라 결과값을 출력하려면,
def extract_indeedjobs(keyword) 에다가
pages = get_page_count(keyword) 코드를 작성하면
extract_indeedjobs 에서 python 이라는 키워드 로 부르면 되며,
그러면 그게 python 키워드로 페이지 개수를 알아내 pages 로 받는다.
받은 페이지 개수만큼 스크랩하는 코드를 실행해야한다.
( def get_page_count(keyword) → 페이지 개수 세주는 함수 )
( def extract_indeed_jobs(keyword) → 페이지 내 구인정보 개수 세주는 함수 )
그러면 extract_indeed_jobs 함수를 페이지 개수에 맞게 실행시켜줘야 하는데
for 문과 range 를 사용해서 실행해본다.
range는 순서 객체를 return 해주는 함수이다.
기존에는 for문 사용해서 5번 반복해줬지만,
for x in [1,2,3,4,5]:
print(x)
range 를 사용하면 간단하게 반복할 수 있다.
( range는 리스트 같은 걸 즉석으로 만들 수 있게 해준다. )
( range는 내가 원하는 만큼의 리스트를 만들어주는 일종의 단축키 이다. )
for i in range(5):
print(i)
출력값:
0
1
2
3
4
range( ) 가 하는거는 ( ) 안에 넣은 값을 가지고 숫자 배열을 만드는 거다.
10개의 숫자 배열을 원하면 숫자 10을 넣으면 된다.
from requests import get
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_page_count(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
search_count = soup.find('div',class_='jobsearch-JobCountAndSortPane-jobCount')
if search_count == None:
print('검색 결과 없음')
else:
search_count2 = search_count.find('span')
print(search_count2.string)
pagination = soup.find('nav',{'aria-label':'pagination'})
pages = pagination.select('div a')
count = len(pages)+1
for page in pages:
if page['aria-label'] == "Previous Page":
count = count - 1
if page['aria-label'] == "Next Page":
count = count - 1
if count >= 5:
return 5
else:
return count
while(True):
pass
def extract_indeed_jobs(keyword):
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(options=options)
pages = get_page_count('python')
for page in range(pages):
base_url = 'https://kr.indeed.com/jobs?q='
browser.get(f'{base_url}{keyword}')
results = []
soup = BeautifulSoup(browser.page_source,'html.parser')
job_list = soup.find('ul', class_='jobsearch-ResultsList')
jobs = job_list.find_all('li', recursive=False)
for job in jobs:
zone = job.find('div', class_='mosaic-zone')
if zone == None:
anchor = job.select_one('h2 a')
title = anchor['aria-label']
link = anchor['href']
company = job.find('span',class_='companyName')
location = job.find('div',class_='companyLocation')
job_data = {
'link':f'https://kr.indeed.com{link}',
'company': company.string,
'location': location.string,
'position': title
}
results.append(job_data)
for result in results:
print(result,'\n////////\n')
while(True):
pass
python 웹 스크래퍼 참고 강의
https://nomadcoders.co/python-for-beginners/lobby
selenium 참고 강의
'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글
Python webscrapper 파일 2개 합치기 (0) | 2022.12.07 |
---|---|
Python selenium 활용해서 webscrapper 기초 제작 6 (0) | 2022.12.06 |
Python selenium 활용해서 webscrapper 기초 제작 4 (0) | 2022.12.02 |
Python selenium 활용해서 webscrapper 기초 제작 3 (0) | 2022.12.01 |
Python None (0) | 2022.11.30 |