ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 독학 12일차 refactor 리팩터링
    coding 2022. 9. 12. 00:00

    이전 포스팅에 만든 weworkremotely 홈페이지 파싱의 코드를 재사용하기 위해 정리를 해주었다.

    extractors라는 폴더를 만들고

    하위에 wwr.py 파일을 만든 뒤 코드를 복사해주었다.

    from requests import get
    #beautifulsoup 사용을 위해 임포트
    from bs4 import BeautifulSoup
    
    def extract_wwr_jobs(keyword):
      #웹을 가져오기 위해 requests의 get을 임포트
      
      base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="
      
      #나중에 url과 검색어를 변경하여 재사용할 수 있게 f문자열 포매팅
      response = get(f"{base_url}+{keyword}")
      #웹사이트에서 정상적인 응답(200)을 주지 않을때를 대비
      if not response.status_code == 200:
        print("Can't request website")
      #정상이라면 페이지의 html 코드를 쫙 긁어 옴
      else:
        #for loop의 밖에서 비어있는 result list 생성
        results = []
        #print(response.text)
        soup = BeautifulSoup(response.text, 'html.parser')
        #section의 jobs클래스 리스트를 만들어주자
        jobs = soup.find_all('section', class_="jobs")
        for job_section in jobs:
          job_posts = job_section.find_all('li')
          #viewlall제거
          job_posts.pop(-1)
          for post in job_posts:
              anchors = post.find_all('a')
              anchor = anchors[1]
            #list의 길이(len)을 알고 있다면 item들의 순서에 맞춰 변수명을 넣어줄 수 있음
              company_name, shift, region = anchor.find_all('span', class_="company")
            
             
              link = anchor['href']
              #find_all은 항상 list를 주기 때문에 title하나만 원해서 .find
              title = anchor.find('span', class_="title")  
              # print(company_name.string,"\n", shift.string,"\n", region.string,"\n", title.string)
              # print("🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸")
      
              job_data = {
                'link': f"https://weworkremotely.com{link}",
                'company_name' : company_name.string,
                'shift' : shift.string,
                'region' : region.string,
                'positon' : title.string
                # "🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸"
              }
              results.append(job_data)
        return results
         # print("🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸")

    그리고 results 값을 print 하는 것이 아닌 return을 받아주었다.

    이 코드를 재사용 하기 위해선,

    재사용을 원하는 폴더에서

    from 폴더이름.파일이름 import 함수

    를 해주면 된다.

    스크래핑 결과와 타겟 사이트의 모습

    이렇게 main.py에서도 코드가 잘 작동하는 모습이다.

    댓글

Designed by Tistory.