3주차_지니뮤직 크롤링

heyryu·2023년 3월 30일
0

vscode로 진행하는데, 출력할 때 한국어 깨짐 문제가 있어서 인코딩을 EUC-KR로 지정해두고
제일 위에 6번째 줄까지 항상 입력해준다.

정답코드와 달랐던 점은 곡의 순위를 출력하는 방식이었는데

#정답코드
rank = tr.select_one('td.number').text[0:2].strip()

#내가 작성한 코드
rank = tr.select_one('td.number')
rank.find('span').decompose()
print(rank.text.strip())

정답코드는 text를 원하는 부분까지만 출력하는 방식을 사용했는데, 100의 자리까지 출력할 것을 고려해 인덱스를 0:2로 지정한 것 같다.
그럴 일은 없겠지만 순위의 자릿수가 늘어난다면,,? 🤔 확장성이 좋지 않을 듯,,,

그래서 난 내가 해낸 코드가 맘에 든다!ㅋㅋㅋ 무슨 문제가 있을진... 아직은 모르지만? ㅎ

아무튼! 계속 오류가 났던 점은 select('상위태그>하위태그>하위태그')를 이용해 td태그인 td.number을 찾아갔고, span태그를 찾아 제거해주는 과정을 한번에 rank 값에 넣으려고 했던 것이다.
쭉 이어서 적었더니 오류 나는 걸 보니 뭘 제거해야하는지 모르는건가... 함수를 실행시켜서 그런가...
암튼 나눠서 적었더니 됐고, 이후에 text로 빼내는 과정, 앞 뒤 공백을 제거해주는 strip()함수를 이용해 출력할 수 있었다.

숙제 코드

참고로 data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers) 이 부분에서 ymd=부분을 어제 날짜로 바꿔주면 어제의 곡 순위도 볼 수 있다 ^_^ (일간 순위라서 오늘 날짜는 안됩니당)

#-*- coding: euc-kr -*-
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

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=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers)

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

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

for tr in trs:
    a_tag = tr.select_one('td.info > a.title.ellipsis')

    if a_tag is not None:
        #temp = tr.find('span').decompose().text
        rank = tr.select_one('td.number')
        rank.find('span').decompose()
        title = a_tag.text.strip()
        artist = tr.select_one('td.info > a.artist.ellipsis').text.strip()
        print(rank.text.strip(), title, artist)

출력

그래서 난 어제 날짜로 출력해봄 ^_^
끝까지 다 캡쳐는 못했지만 50위까지 잘 나온다!

재밌었던 이번 강의 후기를 끝으로 이만~~~

profile
못하면 열심히 하는 게 당연하니까💪 [Frontend/서비스기획]

0개의 댓글