본문 바로가기

Programming

[Python][문법] 기초 - 9. 참고 (크롤링 관련)

반응형
#!/usr/bin/env python
# coding: utf-8

# # 참고: naver music

# In[ ]:


import urllib
import requests
from bs4 import BeautifulSoup as bs
import re


# In[ ]:


# naver 뮤직의 Psy의 New Face 가사 주소


r = requests.get(url)

bs_rt = bs(r.text, "html.parser")
lyric = bs_rt.find("div", id="lyricText")
text  = re.sub(r"<.*?>", "\\n", str(lyric))

print (text)

psy_list = text.split()
psy_set = set(psy_list)
psy_set


# In[ ]:



r2 = requests.get(url2)

naver_music = bs(r2.text, "html.parser")

result = naver_music.find_all("a", title="가사")
title  = naver_music.find_all("span", class_="ellipsis")


# In[ ]:


title = naver_music.find_all("a", class_=re.compile("^_title"))


# In[ ]:


singer = naver_music.find_all("td", class_=re.compile("^_artist artist"))


# In[ ]:


singer_list = []

for idx, xx in enumerate(singer):
    if(idx == 0): continue
   
    print (idx, xx.text.strip())
    singer_list.append(xx.text.strip())


# In[ ]:


title_list = []

for idx, xx in enumerate(title):
    print (idx + 1, xx.text.strip())
    title_list.append(xx.text.strip())


# In[ ]:


p = re.compile(r"[0-9]{4,10}")
all_music = p.findall(str(result))


# In[ ]:


all_music


# In[ ]:


len(all_music)


# In[ ]:


# 이 아래 소스는 네이버 뮤직에서 가사를 가져오는 소스이다.
# 최신 인기가요 50곡의 가사를 출력한다.
# 매일 매일 순위가 변경된다.



for idx, xxx in enumerate(all_music):
    url = "{}{}".format(url_pre, xxx)
    #print (url)
    r = requests.get(url)

    bs_rt = bs(r.text, "html.parser")
    lyric = bs_rt.find("div", id="lyricText")
    text = re.sub(r"<.*?>", "\\n", str(lyric))
    print (title_list[idx])
    print (text)
    try:
        f = open('data/' + '{:02d}_'.format(idx+1) + title_list[idx] + '.txt', 'w', encoding='utf-8')
        f.write(text)
        f.close()
    except:
        pass


# ---

# In[ ]:


# end of file


# In[ ]:





반응형
LIST