欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用urllib模块开发的多线程豆瓣小站mp3下载器

程序员文章站 2022-11-02 20:17:47
复制代码 代码如下:#! /usr/bin/python2.7# -- coding:utf-8 -- import os, urllib,urllib2, thread...

复制代码 代码如下:

#! /usr/bin/python2.7
# -- coding:utf-8 --

import os, urllib,urllib2, thread,threading
import re

#匹配音乐url
reg=re.compile('{"name":"(.+?)".+?"rawurl":"(.+?)",.+?}', re.i)


class downloader(threading.thread):
        def __init__(self, url, name):
                threading.thread.__init__(self)
                self.url=url
                self.name=name

        def run(self):
                print 'downloading from %s' % self.url
                urllib.urlretrieve(self.url, self.name)

threads=[]

#多线程下载文件
def main(url):
        response=urllib.urlopen(url)
        text=response.read()
        groups=re.finditer(reg, text)
        for g in groups:
                name=g.group(1).strip() + ".mp3"
                path=g.group(2).replace('\\', '')
                t=downloader(path, name)
                threads.append(t)
                t.start()

                                                                                                                                                     
if __name__ == '__main__':
        main("http://site.douban.com/huazhou/")
        for t in threads:
                t.join()