Programming/Python 웹 스크래퍼 만들기

Python Refactor

2022. 11. 25. 21:00

5.10 Refactor

 

Refactor : 결과의 변경 없이 코드의 구조를 재조정함. - 가독성을 높이고 유지보수를 편하게 한다.

 

코드를 삭제하기는 싫고 재사용하기 위해

아래 코드를 별도의 파일로 이동시키고 function 안에 넣으려고 한다.

from requests import get
from bs4 import BeautifulSoup

base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="
search_term = "python"

response = get(f'{base_url}{search_term}')
if response.status_code != 200:
    print("Can't request website")
else:
    results =[]
    soup = BeautifulSoup(response.text,'html.parser')
    jobs = soup.find_all('section', class_="jobs")
    for job_section in jobs:
        job_posts = job_section.find_all('li')
        job_posts.pop(-1)
        for post in job_posts:
            anchors = post.find_all('a')
            anchor = anchors[1]
            link = anchor['href']
            company, kind, region = anchor.find_all('span',class_='company')
            title = anchor.find('span', class_='title')
            job_data = {
                'link': f"https://weworkremotely.com/{link}" ,
                'company': company.string,
                'time': kind.string,
                'region': region.string,
                'position': title.string
            }
            results.append(job_data)
    for result in results:
        print(result)
        print('/////////////////')

vs code 에서  extractors 라는 폴더를 만들고 wwr.py 파일을 만든 후 

extract_jobs 라는 function 을 만든다.

extract_jobs는 키워드를 받게된다.

python, react, java 처럼 내가 원하는 키워드를 넘겨준다.

기존의 main.py 에서 아래 코드를 복사하고

from requests import get
from bs4 import BeautifulSoup

아래 코드는 잘라내기해서 wwr.py 파일에 붙여넣는다.

    base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="
    search_term = "python"

    response = get(f'{base_url}{search_term}')
    if response.status_code != 200:
        print("Can't request website")
    else:
        results =[]
        soup = BeautifulSoup(response.text,'html.parser')
        jobs = soup.find_all('section', class_="jobs")
        for job_section in jobs:
            job_posts = job_section.find_all('li')
            job_posts.pop(-1)
            for post in job_posts:
                anchors = post.find_all('a')
                anchor = anchors[1]
                link = anchor['href']
                company, kind, region = anchor.find_all('span',class_='company')
                title = anchor.find('span', class_='title')
                job_data = {
                    'link': f"https://weworkremotely.com/{link}" ,
                    'company': company.string,
                    'time': kind.string,
                    'region': region.string,
                    'position': title.string
                }
                results.append(job_data)
        for result in results:
            print(result)
            print('/////////////////')

이제 키워드는 search_term 을 대체하니 코드를 수정해준다.

search_term 변수 삭제 후

response = get(f'{base_url}{keyword}') 로 변경

from requests import get
from bs4 import BeautifulSoup

def extract_jobs(keyword):
    base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

    response = get(f'{base_url}{keyword}')
    if response.status_code != 200:
        print("Can't request website")
    else:
        results =[]
        soup = BeautifulSoup(response.text,'html.parser')
        jobs = soup.find_all('section', class_="jobs")
        for job_section in jobs:
            job_posts = job_section.find_all('li')
            job_posts.pop(-1)
            for post in job_posts:
                anchors = post.find_all('a')
                anchor = anchors[1]
                link = anchor['href']
                company, kind, region = anchor.find_all('span',class_='company')
                title = anchor.find('span', class_='title')
                job_data = {
                    'link': f"https://weworkremotely.com/{link}" ,
                    'company': company.string,
                    'time': kind.string,
                    'region': region.string,
                    'position': title.string
                }
                results.append(job_data)
        for result in results:
            print(result)
            print('/////////////////')

jobs 를 추출한건 코드에서 print만 하려고 한게 아니라

엑셀에 데이터를 저장하려고 하는게 목표다.

results 를 return 으로 변경한다.

return은 사용자가 function 밖에서 값을 얻을 수 있다는 것을 의미한다.

나중에 indeed 에서도 job들을 추출할 예정이라

extract_jobs → extract_wwr_jobs 로 변경한다.

 

< extractors 폴더의 wwr.py 코드 >

from requests import get
from bs4 import BeautifulSoup

def extract_wwr_jobs(keyword):
    base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

    response = get(f'{base_url}{keyword}')
    if response.status_code != 200:
        print("Can't request website")
    else:
        results =[]
        soup = BeautifulSoup(response.text,'html.parser')
        jobs = soup.find_all('section', class_="jobs")
        for job_section in jobs:
            job_posts = job_section.find_all('li')
            job_posts.pop(-1)
            for post in job_posts:
                anchors = post.find_all('a')
                anchor = anchors[1]
                link = anchor['href']
                company, kind, region = anchor.find_all('span',class_='company')
                title = anchor.find('span', class_='title')
                job_data = {
                    'link': f"https://weworkremotely.com/{link}" ,
                    'company': company.string,
                    'time': kind.string,
                    'region': region.string,
                    'position': title.string
                }
                results.append(job_data)
        return results

모든 코드를 extract_wwr_jobs fuction 안에 넣었다.

이 fuction 은 extractor 폴더 안에 있으며 wwr.py 파일 안에 저장했다.

keyword 를 더한 url 을 검색해서 데이터를 가져오기 때문에

jobs = extract_wwr_jobs( ) 안에 찾고 싶은 단어를 입력하면 된다.

ex) python, java, react 등등

 

< main.py 코드 >

from requests import get
from bs4 import BeautifulSoup
from extractors.wwr import extract_wwr_jobs

jobs = extract_wwr_jobs('python')
print(jobs)

main.py 에서 코드를 실행시키면 extractor 폴더의 wwr.py 파일이 작동한다.

직접 만든 function 을 import 하는 방법

→ from 폴더이름.파일이름 import function 이름     ( 예시 )

→ from extractors.wwr import extract_wwr_jobs  ( 실제 적용 )

폴더명과 파일명, function의 이름이 동일해야 한다.

 

만약 cannot import name 'extract_wwr_jobs' from 'extractors.wwr' 이런 에러가 발생한다면,

python 코드를 저장하는 폴더의 이름을 다른 이름으로 바꿔서 다시 시도해본다.

폴더명을 coding 으로 변경하니 위 에러가 사라지고 결과가 반환되었다. 

 

출력값:

'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글

Python selenium 활용해서 webscrapper 기초 제작 2  (0) 2022.11.29
Python selenium 활용해서 webscrapper 기초 제작 1  (1) 2022.11.28
Python Beautifulsoup 복습  (0) 2022.11.24
Python Beautifulsoup를 이용한 Saving Results  (0) 2022.11.23
Python Job Extraction  (0) 2022.11.22
'Programming/Python 웹 스크래퍼 만들기' 카테고리의 다른 글
  • Python selenium 활용해서 webscrapper 기초 제작 2
  • Python selenium 활용해서 webscrapper 기초 제작 1
  • Python Beautifulsoup 복습
  • Python Beautifulsoup를 이용한 Saving Results
Security Engineer
Security Engineer
IT 공부
Security Engineer
IT-log
Security Engineer
전체
오늘
어제
  • 분류 전체보기 (171)
    • Programming (39)
      • Python 웹 스크래퍼 만들기 (39)
    • IT 지식 (64)
      • IT 정보 (27)
      • CS 기초 (24)
      • 운영체제 (8)
      • IT 인프라 기초 (5)
    • 보안 (45)
      • 악성코드 분석 (10)
      • Bandit 워게임 (25)
      • 취미로 해킹 2 (6)
      • 환경 구축 (4)
    • 웹 해킹 (23)
      • 웹 기초 지식 (8)
      • SQL 기본 (2)
      • 웹 해킹 및 시큐어 코딩 기초 (13)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • CSS
  • 웹 해킹
  • HTML
  • 악성코드
  • 웹 개발
  • bandit
  • 컴퓨터
  • WarGame
  • Selenium
  • 운영체제
  • 리눅스
  • 취미로 해킹
  • CS
  • 워게임
  • 해킹
  • 시큐어 코딩
  • 파이썬
  • flask
  • CS 기초
  • Python
  • Web
  • 모의해킹
  • IT 인프라
  • 취미로해킹
  • overthewire
  • 웹
  • Beautifulsoup
  • Def
  • webScrapper
  • 악성코드 분석

최근 댓글

최근 글

hELLO · Designed By 정상우.
Security Engineer
Python Refactor
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.