[Python] 지니뮤직 사이트 스크래핑 🎵

hyeonbin·2023년 1월 25일

웹 개발

목록 보기
6/9
post-thumbnail

📃 지니뮤직 1~50위 곡 스크래핑

💡 To Do List

  • 지니뮤직 사이트 탐색
  • 순위 / 곡 제목 / 가수 스크래핑


💡 필수 프로그램 설치

  • Pycharm Professional 설치
  • JetBrains 회원가입
  • Python 3.8.6 버전 설치
    → 설치할 때 Add Python 3.8 to PATH 체크!
  • Git bash 다운로드 (윈도우만)


💡 사이트 링크

https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701



💡 순위 / 곡 제목 / 가수 스크래핑

.text[0:2]

  • 원하는 부분을 추츨(슬라이싱) 하기
.text[start:end]
  
title = "룰루랄라랄랄"
result = title.text[0:4]
  
# 출력
룰루랄라

.strip() 함수

  • 양측 공백 제거
    - 문자열.strip()
    - 문자열 양 끝에 있는 공백을 제거해주고, 공백을 제거한 새로운 문자열을 반환
title = " 룰 루 랄 라 랄 랄 "

result = title.strip()

print(f"전 : |{title}|")
print(f"후 : |{result}|")

# 출력
# 전 : | 룰 루 랄 라 랄 랄 |
# 후 : |룰 루 랄 라 랄 랄|



❎ 문제 발생

  • 원하는 부분 추출하니, 15위 쓸데없는 공백 발생


✅ 문제 해결

.replace() 함수

  • 모든 공백 제거
    - 문자열.replace (old, new)
    - 공백없는 문자열 = 공백있는 문자열.replace (" ", "")
    - 첫 번째 인자에 " "공백을 넣고, 두 번째 인자에 "" 빈 문자열 넣기
title = " 룰 루 랄 라 랄 랄 "
  
result = title.replace(" ", "")
  
print(f"전 : |{title}|")
print(f"후 : |{result}|")
  
# 출력
# 전 : | 룰 루 랄 라 랄 랄 |
# 후 : |룰루랄라랄랄|
  
# \n은 줄바꿈!



💡 전체 코드

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:
	rank = tr.select_one('td.number').text[0:2].strip()
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    artist = tr.select_one('td.info > a.artist.ellipsis').text
    if "19금" in title:
    	title = title.replace("\n", " ");
        title = title.replace("  ", "")
    print(rank, title, artist)
profile
할 수 있다고 믿는 사람은 결국 그렇게 된다 😄😊

0개의 댓글