1. 程式人生 > >Python 爬取喜馬拉雅FM中‘冬吳同學會’專輯

Python 爬取喜馬拉雅FM中‘冬吳同學會’專輯

一、前言

在這篇文章中,其實也可以沒有這個前言,直接上程式碼最好。因為也並不是很難,直接抓包,模擬瀏覽器請求,拿到音訊介面資訊就完了。但是但是,我是可以批量下載或者抓取喜馬拉雅所有的音訊,但是這對於我並沒有太多的意義。我想做的就是為後面我即將開發一個自己的資源平臺做準備。而我對於電臺的執著現在就只剩‘冬吳同學會’了,畢竟我是他8年的忠實粉絲。從剛開始的‘冬吳相對論’,到停播後的想念,再到今年6月份開播,歷經起起伏伏,但也是堅持下來了。我的心智模式也潛移默化的因它而改變。

我就是想打廣告,發自內心的想為他們打廣告。‘冬吳同學會’,每週二、四 「晚八點」 更新內容 每週兩期,依然坐著打通經濟生活任督二脈。每期內容從當下熱點的社會、經濟現象談起,解讀背後的真實道理。打破以往財經節目嚴肅有餘的紙媒化傾向,將輕鬆、睿智、人性化、平民化的表達手段充分融入到內容中來,從生活的視角解讀經濟事件的玄機,在經濟話題的背後探討生活的真諦。更輕鬆的商業、哲思、生活視角,讓我們與樑同學、老吳同學一道對這個世界心生歡喜,充滿好奇。

這裡寫圖片描述

二、Python 爬取程式碼

*1. ximalayaFM.py*

# -*- coding:utf-8 -*-
"""利用request爬取喜馬拉雅FM裡‘冬吳同學會’專輯所有音訊
    實現 1.下載音訊到本地
        2. 將json中重要資訊(url介面等等)存在mongodb資料庫
    __author__ = 'LuyiBuddha'
"""
import os

import requests
from lxml import etree
import sys
import db_model

reload(sys)
sys.setdefaultencoding('utf-8'
) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' } def get_audio(): title = u'冬吳同學會' start_url = 'http://www.ximalaya.com/83432108/album/8475135/' response = requests.get(start_url, headers=headers).text num_list = etree.HTML(response).xpath('//div[@class="personal_body"]/@sound_ids'
)[0].split(',') mkdir(title) os.chdir(r'D:\ximalayaFM\\' + title) for id in num_list: json_url = 'http://www.ximalaya.com/tracks/{}.json'.format(id) html = requests.get(json_url, headers=headers).json() print html audio_url = html.get('play_path') title = html.get('title') download(audio_url, title) dm.add_one(title, audio_url) print '{0}, 下載和加入資料庫完畢'.format(title) def mkdir(title): path = r'D:\ximalayaFM\\' isExists = os.path.exists(os.path.join(path, title)) if not isExists: print (u'建立一個名子叫做{}的資料夾'.format(title)) os.makedirs(os.path.join(path, title)) return True def download(url, title): title = title + '.m4a' content = requests.get(url).content # 返回的是二進位制(常用於圖片,音訊,視訊) with open(title, 'wb') as f: f.write(content) if __name__ == '__main__': dm = db_model.DongWu_Mongo() get_audio() # rows = dm.get_more() # for row in rows: # print row.title + ',' + row.audio_url

*2.db_model.py(資料模型例項化)*

# -*- coding:UTF-8 -*-
from mongoengine import *


class DongWu(Document):
    """冬吳例項"""
    title = StringField(required=True)
    audio_url = StringField(required=True)

    meta = {
        'collection': 'Dongwu',
    }


class DongWu_Mongo(object):
    def __init__(self):
        connect('ximalaya')

    def add_one(self, title, audio_url):
        """新增一條資料到資料庫"""
        DongWu_obj = DongWu(
            title=title,
            audio_url=audio_url
        )
        DongWu_obj.save()
        return DongWu_obj

    def get_one(self):
        """查詢一條資料"""
        return DongWu.objects.first()

    def get_more(self):
        """查詢多條資料"""
        return DongWu.objects.all()

    def get_from_oid(self, oid):
        """根據ID來獲取資料"""
        return DongWu.objects.filter(pk=oid).first()