当前位置: 移动技术网 > IT编程>脚本编程>Python > BeautifulSoup与aiohttp的简单应用-爬取《网上中华五千年》音频

BeautifulSoup与aiohttp的简单应用-爬取《网上中华五千年》音频

2019年05月12日  | 移动技术网IT编程  | 我要评论

封神之黄天化,ca4587,航天胶水

  香港电台的节目素质都比较不错,其中有个《中华五千年》的节目是以情景剧与旁白的形式来展示历史故事,由传说时代一直到民国,1983年首播至2000年,非常长寿的一个节目。网上能找到版本声音非常模糊,不过在其《网上中华五千年》的网站上可以在线收听所有节目。虽然可以在线听,但要science上网,而且在线听中断了就不能再续着听,很难受。因此,就想到利用python来的爬虫来把节目都下载下来慢慢听。

  

分析html页面

  在浏览器打开审查元素找到音频的链接标签,发现链接都在class为.listen-button的a标签里。只要定位到这个标签,取出text作为文件名,href作为下载url就可以了。

代码实现

  代码很简单,首先,主体结构是这样的:

'''
    下载中华五千年
'''
from bs4 import beautifulsoup
import requests,urllib,re
import time
import aiohttp
import asyncio
import os

async def main():
    start_page = 1
    while true:     
        url = 'http://rthk9.rthk.hk/chiculture/fivethousandyears/subpage{0}.htm'.format(start_page)
        soup = await geturl(url)      #取html内容
        if not soup.title: return   #直到无内容退出
        title = soup.title.text 
        title = title[title.rfind(' ')+1:]
        listenbutton = soup.select(".listen-button") #查出所有.listen-button类的标签
        #根据title 创建相应的文件夹
        rootpath = './中华五千年/'
        if not os.path.exists(rootpath + title):
            os.makedirs(rootpath + title)

        for l in listenbutton:
            if  l.text != "":
                href = l['href']
                filename  = str(title) +'_' + str(l.text)
                if filename.find('公元') > -1
                    await download(filename=filename,url=href,title=title)  #下载语音
start_page += 1 #下一页 asyncio.run(main())

其中异步函数(协程)geturl :

async def geturl(url):
    async with aiohttp.clientsession() as session:
        #因需science上网所以需要本地代理
        async with session.get(url,proxy='http://127.0.0.1:1080') as resp:
            wb_data = await resp.text()
            soup = beautifulsoup(wb_data,'lxml')
    return soup

异步下载语音函数  download:

async def download(url,filename,title):
    file_name = './中华五千年/{0}/{1}'.format(title,filename + '.mp3') 
    async with aiohttp.clientsession() as session:
        async with session.get(url,proxy='http://127.0.0.1:1080') as resp:
            with open(file_name, 'wb') as fd:
                while true:
                    chunk = await resp.content.read()
                    if not chunk:
                        break
                    fd.write(chunk)

由于用了异步io的方式,很快便可以下载完一页。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网