웹개발 종합반 3주차_17일(1)

ddabong-dochi·2022년 5월 5일
0
post-thumbnail

☘️지니뮤직의 1~50위 곡을 스크래핑 해보자!

  • 지니뮤직 사이트
  • 순위 / 곡 제목 / 가수를 스크래핑 해보자!
  • 👻힌트

    1) 출력 할 때는 print(rank, title, artist) 사용
    2) 앞에서 두 글자만 끊기! text[0:2] 를 사용하기
    3) 순위와 곡제목이 깔끔하게 나오지 않을 거다. 옆에 여백이 있다던가, 다른 글씨도 나온다던가.. 파이썬 내장 함수인 strip() 구글링 해보기

🔥 내가 작성한 코드 & 생각

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')

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

for song in songs:
    rank = song.select_one('td.number').text[0:2].rstrip()
    title = song.select_one('td.info > a.title.ellipsis').text.lstrip()
    artist = song.select_one('td.info > a.artist.ellipsis').text

    if "19금" in title:
        print(rank, title.strip("19금").lstrip(), artist)
    else:
        print(rank, title, artist)
  1. 일단 크롬에 사이트 켜놓고 어떤 태그가 사용됐고, 어디까지인지 확인했다.
  2. rank를 text로 가져오니 순위 외에 뒤에 '20위 상승' 등의 덧붙는 글자들이 있어서 text[0:2]로 삭제함
  3. title과 artist는 같은 td.info에 있으나 클래스가 달라서 선택자에서 차이가 난다.
  4. print할 시 여백이 매우 존재하기 때문에 rstrip, lstrip로 제거해줬다. 공백 제거하는거 같은데 r이 오른쪽이겠지

❗️여기까지 해줬는데 노래 중 Justin Bieber에 Peaches가 앞에 "19금" 단어가 붙어서 제거해 줘야 한다.

이거 하나만 그런 거라서 text[]로 해보자니 안 될 것 같아서 if 문을 써봤다. title 내에 "19금" 글자가 있으면 제거 하고 공백을 조정하라는...일단 요기까지 내가 해봤는데 잘 된다.

과연 숙제 답안 코드로 올라온 것과 차이가 얼마나 날까?
✔️ 3주차 숙제 답안 코드

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)

이때는 peaches가 없었나; 별 다른 내용이 없네
곡 순위 리스트 중에 제일 좋아하는 노래로 머리를 쓴 게 아이러니🫠

웹개발 종합반 3주차 소감💕

파이썬 패키지를 통한 크롤링과 mongoDB 연결을 배웠다. 1~2주차가 프론트엔드라고 하면 3주차는 백엔드인건가? 구분이 맞나? 암튼 4주차부터 2개가 합쳐진다는데 어떻게 연결하고 진행되는지 궁금하다!
암튼 여기까지는 할만했음😙

profile
비전공자 직장인 개발일지😆

0개의 댓글