본문 바로가기
IT/Web

[프론트엔드] 스파르타코딩클럽 웹개발 종합반 3주차 수강후기

by 퐁시냥 2021. 11. 18.

스파르타코딩클럽 웹개발 종합반 3주차 수강후기.

8주 과정을 5일만에 다 끝내야하는데, 그것도 이틀만에 5주 수업을 다 들어야한다 ㅠㅠ

르탄이는 귀여운데.. 내가 꼴지다 ^0^ 그래도 나처럼 개발일지 다 쓰는 사람은 없겠지 하고 나름의 위로중  

 

스파르타코딩클럽 진도율

 

3주차도 재미있었다. 그동안 파이썬을 이용한 크롤링에 대해서 많이 들어보긴 했지만 실제로 해본적은 없어서, 강의 들으면서 직접 해보는 것도 정말 재미있었음!! 

오늘 4, 5주차도 끝내야겠다.. 열심히해야지 홧팅홧팅

 


[수업 목표]

  1. 파이썬 기초 문법을 안다.
  2. 원하는 페이지를 크롤링 할 수 있다.
  3. pymongo를 통해 mongoDB를 제어할 수 있다.

 

python 문법은 거의 아는 내용이라 쉬웠고, 크롤링 방법(BeautifulSoap 패키지 이용), DB 삽입/삭제(mongoDB 이용)을 배웠다. 

 

01. 패키지 사용해보기

  • Requests 라이브러리 사용해보기 + List/Dictionary/함수/If/For문 연습
    • IDEX_MVL 값이 60 미만인 구만 찍어주자!
    • import requests # requests 라이브러리 설치 필요
      
      r = requests.get('http://spartacodingclub.shop/sparta_api/seoulair')
      rjson = r.json()
      
      gus = rjson['RealtimeCityAir']['row']
      
      for gu in gus:
      	if gu['IDEX_MVL'] < 60:
      		print (gu['MSRSTE_NM'], gu['IDEX_MVL'])

 

02. 웹스크래핑(크롤링) 기초

  • select, select_one 사용법(BeautifulSoup)
    • import requests
      from bs4 import BeautifulSoup
      
      # URL을 읽어서 HTML를 받아오고,
      headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
      data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
      
      # HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
      soup = BeautifulSoup(data.text, 'html.parser')
      
      # select를 이용해서, tr들을 불러오기
      movies = soup.select('#old_content > table > tbody > tr')
      
      # movies (tr들) 의 반복문을 돌리기
      for movie in movies:
          # movie 안에 a 가 있으면,
          a_tag = movie.select_one('td.title > div > a')
          if a_tag is not None:
              # a의 text를 찍어본다.
              print (a_tag.text)
    • # 선택자를 사용하는 방법 (copy selector)
      soup.select('태그명')
      soup.select('.클래스명')
      soup.select('#아이디명')
      
      soup.select('상위태그명 > 하위태그명 > 하위태그명')
      soup.select('상위태그명.클래스명 > 하위태그명.클래스명')
      
      # 태그와 속성값으로 찾는 방법
      soup.select('태그명[속성="값"]')
      
      # 한 개만 가져오고 싶은 경우
      soup.select_one('위와 동일')
    • import requests
      from bs4 import BeautifulSoup
      
      headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
      data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
      
      soup = BeautifulSoup(data.text, 'html.parser')
      
      #old_content > table > tbody > tr:nth-child(3) > td.title > div > a
      #old_content > table > tbody > tr:nth-child(4) > td.title > div > a
      
      movies = soup.select('#old_content > table > tbody > tr')
      
      for movie in movies:
          a = movie.select_one('td.title > div > a')
          if a is not None:
              title = a.text
              rank = movie.select_one('td:nth-child(1) > img')['alt']
              star = movie.select_one('td.point').text
              print(rank, title, star)

 

03. mongoDB - Atlas 사용하기

  1. 패키지 설치 
    • pymongo, dnspython
      
  2. pymongo 사용법
    • 연결하기
      • from pymongo import MongoClient
        client = MongoClient('여기에 URL 입력')
        db = client.dbsparta
    • Insert, Update, Delete
      • # 저장 - 예시
        doc = {'name':'bobby','age':21}
        db.users.insert_one(doc)
        
        # 한 개 찾기 - 예시
        user = db.users.find_one({'name':'bobby'})
        
        # 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
        all_users = list(db.users.find({},{'_id':False}))
        
        # 바꾸기 - 예시
        db.users.update_one({'name':'bobby'},{'$set':{'age':19}})
        
        # 지우기 - 예시
        db.users.delete_one({'name':'bobby'})

 

04. 지니뮤직 크롤링(1~50순위)

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    rank = tr.select_one('td.number').text[0:2].strip()
    artist = tr.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, artist)

댓글