본문 바로가기
Python

Python BeautifulSoup 사용해서 멜론 TOP 100 크롤링 하기

by holy season 2023. 5. 5.
반응형

설치

먼저 python으로 크롤링 하기 위해서는 BeatufulSoup과 requests 모듈이 필요하다 .

pip install 명령어로 관련된 모듈들을 설치한다.

pip install beautifulsoup4
pip install requests

requests 모듈을 이용해서 응답 받아오기

url은 어떤 사이트에 요청을 보낼것인지 주소를 정하고 userAgentHeader는 User-Agent 헤더를 설정한다

requests.get()함수의 인자로 url, headers에 userAgentHeader 값을 할당하고 받아온 내용을 response 변수에 저장한다.

url = 'https://www.melon.com/chart/index.htm'
userAgentHeader = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Whale/3.20.182.14 Safari/537.36'}
response = requests.get(url, headers=userAgentHeader)

예외 처리하기

response의 응답이 200일 경우만 작동하도록 예외처리한다.

if(response.status_code == 200):
else:
	print(response.status_code)

BeautifulSoup로 내용 얻기

response.text로 html의 값을 얻고 BeautifulSoup의 인자로 html과 'html.parser'를 넣어 beautifulSoup를 만든다

원하는 정보를 얻기 위해 멜론 차트 100에 있는 html 태그를 분석하여 beatifulSoup.select() 함수를 사용하여 정보를 얻는다.

    html = response.text
    beautifulSoup = BeautifulSoup(html, 'html.parser')
    rank = beautifulSoup.select('#frm > div > table > tbody > tr > td > div > span.rank')
    songTitle = beautifulSoup.select('#frm > div > table > tbody > tr > td > div > div > div.ellipsis.rank01 > span > a')
    songArtist = beautifulSoup.select('#frm > div > table > tbody > tr > td > div > div > div.ellipsis.rank02 > a')
    
    for i in range(len(rank)) :
        print(rank[i].getText(), songTitle[i].getText(), ' - ' + songArtist[i].getText())

결과

1 부터 100까지 멜론 차트 100에 있는 노래 순위, 제목, 정보 등이 나온다.

 

반응형

'Python' 카테고리의 다른 글

PySide6로 GUI 구성하기  (0) 2023.05.18
Python unittest 사용하기  (0) 2023.05.16
파이썬 실행파일(.exe) 파일 만들기  (0) 2023.05.11
tkinter로 화면 만들기  (0) 2023.05.10
Python venv 가상환경 생성 오류  (1) 2023.05.09