本篇内容主要讲解“如何使用python 批量下载图片”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用python 批量下载图片”吧!
from time import time from threading import Thread import requests class DownloadHanlder(Thread): def __init__(self, url): super().__init__() self.url = url def run(self): filename = self.url[self.url.rfind('/') + 1:] #get the filename from origin url with the value of : # 'https://cache.yisu.com/upload/information/20210521/347/345442.jpg' resp = requests.get(self.url) with open('./pictest/' + filename, 'wb') as f: f.write(resp.content) def main(): # 通过requests模块的get函数获取网络资源 resp = requests.get( '?key=keyvalue4&num=10') # 将服务器返回的JSON格式的数据解析为字典 data_model = resp.json() for mm_dict in data_model['newslist']: url = mm_dict['picUrl'] # 通过多线程的方式实现图片下载 DownloadHanlder(url).start() if __name__ == '__main__': main()线程模块提供了Thread类来处理线程,Thread类提供了以下方法: run(): 用以表示线程活动的方法。 start():启动线程活动。
其中,Thread类中含有方法start() 其定义如下:
def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait()到此,相信大家对“如何使用python 批量下载图片”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。