天天看點

Python-爬取百度音樂

最近閑來無事,無意間就看到了百度音樂,于是就寫了一個小爬蟲來爬取其音樂。

使用的子產品:urllib2,beautifulsoup

urllib2的使用連結:https://docs.python.org/2/library/urllib2.html#

beautifusoup的使用連結https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

首先我們分析網頁:

整個爬蟲的主人口連結:http://music.baidu.com/tag

打開該連結的頁面,分類标簽和分類的連結的html代碼如下

Python-爬取百度音樂

擷取的Python代碼如下

Python-爬取百度音樂

針對每一個分類擷取其相關的所有歌曲,随便打開一個分類頁面進行分析

Python-爬取百度音樂

擷取所有歌曲的Python代碼如下

#擷取該頁面的所有歌曲的内容
def getAllMusic(sourceURL):
    print 'getAllMusic start sourceURL='+sourceURL
    #擷取頁面數量
    sURL=sourceURL+'?start=0&size=20&third_type=0'
    htmlContent=getHTML(sURL)
    soup=BeautifulSoup(htmlContent,'lxml')
    aLists=soup.find_all('div','page-inner')
    if aLists:
        aSoup = BeautifulSoup(str(aLists), 'lxml')
        pageNumberLists = aSoup.find_all('a')
        print pageNumberLists
        if pageNumberLists:
            aStr=pageNumberLists[len(pageNumberLists)-]
            print 'aStr='+str(aStr)
            pageASoup=BeautifulSoup(str(aStr),'lxml')
            pageNumber=int(pageASoup.find('a').get_text())
        else:
            pageNumber=
    else:
        pageNumber=
    print 'pageNumber='+str(pageNumber)
    #擷取該類型的所有歌曲
    count = 
    for i in range(,pageNumber+):
        sURL=sourceURL+'?start='+str(count)+'&size=20&third_type=0'
        print 'sURL='+sURL
        #擷取html頁面
        htmlContent=getHTML(sURL)
        #對頁面進行解析
        soup=BeautifulSoup(htmlContent,'lxml')
        #擷取歌曲類型
        m_type=soup.find('span','title').get_text()
        print 'm_type='+m_type
        #擷取歌曲名和歌曲連結
        spanStr=soup.find('span','song-title')
        spanSoup=BeautifulSoup(str(spanStr),'lxml')
        #擷取歌曲名
        m_name=spanSoup.find('a').get_text()
        print 'm_name=' + m_name
        #擷取歌曲連結
        m_link=baiduMusicRootURL+spanSoup.select_one('a[href]').get('href')
        print 'm_link='+m_link
        #擷取歌手名
        m_singer=soup.find('span','author_list').get_text()
        nStr=m_singer[:]
        if nStr=='\n':
            m_singer=m_singer[:len(m_singer)]
        print 'm_singer len='+str(len(m_singer))
        print 'm_singer='+m_singer
        #擷取專輯
        m_album=soup.find('span','album-title').get_text()
        print 'm_album='+m_album
           

以上是該爬蟲的主要技術分析

下面是整個爬蟲的完整代碼:

#coding=utf-8 #設定編碼
#擷取百度音樂
import urllib2
from bs4 import BeautifulSoup
#百度音樂的根路徑url
baiduMusicRootURL='http://music.baidu.com'
#百度音樂分類的基本的根路徑url
baiduMusicTagURL='http://music.baidu.com/tag'
#擷取音樂的分類标簽
def getMusicTags(musicTagURL):
    print 'getMusicTag='+musicTagURL
    musicTags={}
    htmlContent=getHTML(musicTagURL)
    #print 'getMusicTags='+htmlContent
    #解析網頁,擷取分類标簽
    soup=BeautifulSoup(htmlContent,'lxml')
    Tags=soup.find_all('span','tag-list clearfix')
    #print Tags
    for tag in Tags:
        #擷取連接配接文本内容
        tagName=tag.get_text()
        #擷取連結
        aSoup=BeautifulSoup(str(tag),'lxml')
        a=aSoup.select_one('a[href]')
        tagLink=a.get('href')
        #tagName作為鍵,tagLink作為值儲存到字典中
        musicTags[tagName]=tagLink
    return musicTags
#擷取網頁
def getHTML(musicTagURL):
    print 'getHTML= '+musicTagURL
    headers={}
    request=urllib2.Request(musicTagURL,headers=headers)
    response=urllib2.urlopen(request)
    htmlContent=response.read()
    return htmlContent
#擷取該頁面的所有歌曲的内容
def getAllMusic(sourceURL):
    print 'getAllMusic start sourceURL='+sourceURL
    noData='#'
    try:
        #擷取頁面數量
        size=
        sURL=sourceURL+'?start=0&size=20&third_type=0'
        htmlContent=getHTML(sURL)
        soup=BeautifulSoup(htmlContent,'lxml')
        aLists=soup.find_all('div','page-inner')
        if aLists:
            aSoup = BeautifulSoup(str(aLists), 'lxml')
            pageNumberLists = aSoup.find_all('a')
            #print pageNumberLists
            if pageNumberLists:
               aStr=pageNumberLists[len(pageNumberLists)-]
                #print 'aStr='+str(aStr)
                pageASoup=BeautifulSoup(str(aStr),'lxml')
             pageNumber=int(pageASoup.find('a').get_text())
            else:
                pageNumber=
        else:
            pageNumber=
        print 'pageNumber='+str(pageNumber)
        #擷取該類型的所有歌曲
        count = 
        for i in range(,pageNumber+):
            print 'i='+str(i)
            sURL=''
            try:
                sURL=sourceURL+'?start='+str(count)+'&size=20&third_type=0'
                print 'sURL='+sURL
                #擷取每個頁面上的歌曲
                # 擷取html頁面
                htmlContent = getHTML(sURL)
                # 對頁面進行解析
                soup = BeautifulSoup(htmlContent, 'lxml')
                # 擷取歌曲類型
                m_type= soup.find('span', 'title').get_text()
                print 'm_type=' + m_type
                #擷取歌曲清單
                musicList=soup.find('div','main-body-cont')
                #print 'musicListSoup='+str(musicList)
          musicListSoup=BeautifulSoup(str(musicList),'lxml')
            musicsLists=musicListSoup.find_all('div','song-item')
                print 'musicsLists='+ str(musicsLists)
                print 'musicsLists len='+str(len(musicsLists))
                for music in musicsLists:
                    #print 'music='+str(music)
                 musicSoup=BeautifulSoup(str(music),'lxml')
                    # 擷取歌曲名和歌曲連結
                    spanStr = musicSoup.find('span', 'song-title')
                    spanSoup = BeautifulSoup(str(spanStr), 'lxml')
                    # 擷取歌曲名
                    m_name = spanSoup.find('a').get_text()
                    if not m_name:
                        m_name=noData
                    print 'm_name=' + m_name
                    # 擷取歌曲連結
                    m_link = baiduMusicRootURL + spanSoup.select_one('a[href]').get('href')
                    if not m_link:
                        m_link=noData
                    print 'm_link=' + m_link
                    # 擷取歌手名
                    m_singer = musicSoup.find('span', 'author_list').get_text()
                    #第一個字元是‘\n’
                    if m_singer and len(m_singer)>:
                        nStr = m_singer[:]
                        if nStr == '\n':
                            m_singer = m_singer[:len(m_singer)]
                    else:
                        m_singer=noData
                    print 'm_singer len=' + str(len(m_singer))
                    print 'm_singer=' + m_singer
                    # 擷取專輯
                    m_album = musicSoup.find('span', 'album-title').get_text()
                    if not m_album:
                        m_album='#'
                    print 'm_album=' + m_album
                    # 擷取(設定)點播量
                    m_click = 
                    # 擷取(設定)收藏量
                    m_collect = 
                count = count + 
            except:
                pass
    except:
        pass
#主程式
if __name__ == '__main__':
    print 'Music Spider start'
    #擷取百度音樂的分類标簽
    musicTags=getMusicTags(baiduMusicTagURL)
    print musicTags
    #按照分類爬取音樂
    for k,v in musicTags.items():
        print 'k='+k
        print 'v='+str(v)
        httpStr=str(v)[:]
        if httpStr=='http://':
            sourceURL=str(v)
        else:
            sourceURL=baiduMusicRootURL+str(v)
        print 'sourceURL='+sourceURL
        #擷取歌曲
        getAllMusic(sourceURL)
           

不喜勿噴