본문으로 바로가기

네이버 노래 가사 파싱하기

category Coding/Python 2016. 12. 1. 23:36
반응형

친구가 앨범에 있는 모든 가사들을 다운받아서 저장하는 작업을 손으로 하고 있길래

파싱해주는 코드를 짜줬다.


----------------------------------------------------------------------------------------------------------------------------------------------------

#-*- coding: utf-8 -*-

import requests

import re


header = {

    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',

    'Content-Type':'application/x-www-form-urlencoded; charset=utf-8',

    'Referer':'http://blog.naver.com/BuddyAdd.nhn'}


r = requests.get("http://music.naver.com/album/index.nhn?albumId=123456")

pattern = "<a href=\"#(.*?)\" class=\"_title title"

r1 = re.findall(pattern, r.text)

#print r1

song_pattern = "title=\"(.*?)\" ><span class=\"ellipsis\">"

song = re.findall(song_pattern, r.text)

#print r2


for i in range(0,len(r1)):


    go = requests.get("http://music.naver.com/lyric/index.nhn?trackId="+r1[i])

    pattern2 = "<div id=\"lyricText\" class=\"show_lyrics\">(.*?)</div>"

    r2 = re.findall(pattern2, go.text)

    last = r2[0].encode('utf8').replace('<br />', '\n')


    f = open("./file/"+str(song[i].encode('utf8')), 'w')

    f.write(last)

    f.close()

    print "["+str(i)+"] Done"

----------------------------------------------------------------------------------------------------------------------------------------------------

빨간색으로 123456 이라고 되어있는 부분에 앨범번호를 적으면 된다.


(빨간색으로 네모친 부분의 번호)


실행시키면 file 디렉토리에 노래제목으로 가사를 저장한다.



[다운로드]

song.py

반응형