python-------利用多进程,多线程写一个下载器代码

利用多进程写一个下载器

from multiprocessing import Process
from urllib import request
def downloder(url,isPicture=1):
    file_name=url.split('/')[-1]
    response=request.urlopen(url)
    content=response.read()
    if isPicture==1:
        with open(file_name,'wb') as fq:
            fq.write(content)
    else:
        content=content.decode('utf-8')
        with open(file_name,'w',encoding='utf-8') as fq:
            fq.write(content)
if __name__ == '__main__':
    url_list=['https://p1.ssl.qhimg.com/t0151320b1d0fc50be8.png'
        ,'https://p0.ssl.qhimg.com/t01840823620d908ff2.png',
              'http://lianghui.people.com.cn/2019npc/n1/2019/0316/c425476-30978927.html'
    ]
    for url in url_list:
        p=Process(target=downloder,args=(url,))
        p.start()

利用多线程写一个下载器

from threading import Thread
from urllib import request
class Thresd_class(Thread):
    def __init__(self,url):
        Thread.__init__(self)
        self.url=url
    def run(self,isPicture=1):
        file_name=self.url.split('/')[-1]
        response=request.urlopen(self.url)
        content=response.read()
        if isPicture==1:
            with open(file_name,'wb') as fq:
                fq.write(content)
        else:
            content=content.decode('utf-8')
            with open(file_name,'w',encoding='utf-8') as fq:
                fq.write(content)
if __name__ == '__main__':
    url_list=['http://kf.qq.com/faq/170101iEzyqa170101vyE7Vv.html'
              ,'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2437668214,2147435278&fm=26&gp=0.jpg'
            ,'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3843445883,2974888073&fm=26&gp=0.jpg'
    ]
    for url in url_list:
        t=Thresd_class(url)
        t.start()

猜你喜欢

转载自blog.csdn.net/python20180218/article/details/88597466