Python实现的下载8000首儿歌的代码分享

yipeiwu_com5年前Python基础

下载8000首儿歌的python的代码:

复制代码 代码如下:

#-*- coding: UTF-8 -*-

from pyquery import PyQuery as py
from lxml import etree
import urllib
import re
import os
import sys
import logging

def format(filename):
    tuple=(' ',''','\'')
    for char in tuple:
        if (filename.find(char)!=-1):
            filename=filename.replace(char,"_")
    return filename

def download_mp3(mp3_url, filename,dir):      
    f = dir+"\\"+filename
    if os.path.exists(f):
      logger.debug(f+" is existed.")
      return
     
    try:
        open(f, 'wb').write(urllib.urlopen(mp3_url).read())
        logger.debug(  filename + ' is downloaded.')
    except:
        logger.debug( filename + ' is not downloaded.')

       
def download_all_mp3(start,end,dir,logger):
  for x in range(start,end):
    try:
        url = "http://www.youban.com/mp3-d" + str(x) + ".html"
        logger.debug(str(x) + ": "+url)
        doc = py(url=url)
        e = doc('.mp3downloadbox')
        if e is None or e == '':
          logger.debug(url+" is not existed.")
          return
         
        e = unicode(e)
        #logger.debug( e)
        regex = re.compile(ur".*<h1>(.*)</h1>.*downloadboxlist.*?<a.*?\"(.*?)\"",re.UNICODE|re.S)
        m = regex.search(e)
        if m is not None:
          title = m.group(1).strip()
          title2 = str(x)+"_"+title + ".mp3"
          #title2 = re.sub(' ','_',title2)
          title2 = format(title2)
          link = m.group(2)
          #logger.debug( "title:" + title + " link:" + link)
          if link == '' or title == '':
            logger.debug(url + " is not useful")
            continue
          logger.debug(str(x)+": "+link)
          download_mp3(link,title2,dir)
    except:
        logger.debug(url+" met exception.")
        continue
     

     
if __name__ == "__main__":
    dir_root = "e:\\song"
    if sys.argv[3] != '': dir_root=sys.argv[3]
   
    start,end = 1,8000
    if sys.argv[1] >= 0 and sys.argv[2]>=0:
      start,end = int(sys.argv[1]),int(sys.argv[2])
      print ("Download from %s to %s.\n" % (start,end))     
   
    dir = dir_root + "\\"+str(start)+"-"+str(end)
    if not os.path.exists(dir):
      os.mkdir(dir)    
    print "Download to " + dir + ".\n"
   
    logger = logging.getLogger("simple")
    logger.setLevel(logging.DEBUG) 
    fh = logging.FileHandler(dir+"\\"+"download.log")
    ch = logging.StreamHandler()
    formatter = logging.Formatter("%(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)
    download_all_mp3(start,end,dir,logger)

有需要的可以参考继续修改。

相关文章

Python实现SVN的目录周期性备份实例

本文实例讲述了Python实现SVN的目录周期性备份方法。分享给大家供大家参考。具体如下: 起因:今天用SVN时,不小心把远程SVN服务器上的目录删掉了,然后在本地又手贱地还原了一下项目...

Win10下Python3.7.3安装教程图解

Win10下Python3.7.3安装教程图解

        到2019年初,Python3已经更新到了Python3.7.3,Python有两个大版本Pytho...

Python字典及字典基本操作方法详解

本文实例讲述了Python字典及字典基本操作方法。分享给大家供大家参考,具体如下: 字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。...

初学python数组的处理代码

初学python,小缘缘出了几道题: 有一 list a = [1, 2, 3, 4, 5, 6] 请将 a 依 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输出,...

跟老齐学Python之从if开始语句的征程

跟老齐学Python之从if开始语句的征程

一般编程的教材,都是要把所有的变量类型讲完,然后才讲语句。这种讲法,其实不符合学习的特点。学习,就是要循序渐进的。在这点上,我可以很吹一通了,因为我做过教师,研究教育教学,算是有一点心得...