ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 독학 11일차 BeautifulSoup(웹 파싱하기, 스크래핑) 5
    coding 2022. 9. 11. 00:00

    이번 포스팅에선 깔끔하게 스크래핑 해온 아래의 데이터 결과를 한 곳에 저장해보자.

    회사명, 근무 시간, 지역 등의 key 값이 있으니 무언가 떠오르지 않는가?

    정답이다. 바로 파이썬의 dictionary데이터 타입을 이용해 정리해보자.

     

    1. 가장먼저 for loop의 밖에 비어 있는 results = [ ]리스트를 만들어주고

    2. 가져온 스트링 값들을 job_data의 dic에 key값과 함께 정리해주고

    3. .append를 사용해 튜플 값을 리스트에 넣어준다.

    4. for loop의 밖에서 result 값을 출력해주면 끝

    더보기
    #웹을 가져오기 위해 requests의 get을 임포트
    from requests import get
    #beautifulsoup 사용을 위해 임포트
    from bs4 import BeautifulSoup
    
    base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="
    search_term = "python"
    
    #나중에 url과 검색어를 변경하여 재사용할 수 있게 f문자열 포매팅
    response = get(f"{base_url}+{search_term}")
    #웹사이트에서 정상적인 응답(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 = {
              'company_name' : company_name.string,
              'shift' : shift.string,
              'region' : region.string,
              'positon' : title.string
            }
            results.append(job_data)
      #for loop의 밖에서 result 출력
      for result in results: 
        print(result)
        print("🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸🔸")

    그러면 이렇게도 아름다운 결과물이 생성이 된다.

    출력 결과

    가슴이 웅장해지는 웹 스크래핑, 나이키의 드로우 목록을 스크랩하는 웹 페이지를 제작해 봐야겠다.

    댓글

Designed by Tistory.