您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 东莞分类信息网,免费分类信息发布

Python多线程threading—图片下载

2023/11/14 1:56:36发布18次查看
上一篇,写了一个爬壁纸图片的小爬虫:python爬虫入门—图片下载下载效果太慢了,于是乎想到了用多线程改造一下,看看速度能提高多少!
虽然说,由于gil锁(global interpreter lock)的存在,python的多线程不是真正意义上的多线程,一个时间段内,一个cpu只能执行一个线程。但是在爬虫相关的程序上,经常出现io密集型任务多cpu密集型任务少的情况,大多数时间都在等get、post请求、收发数据(对于本次的爬虫图片下载程序,更是如此)。于是可以用python的多线程来实现加速,即一个线程在get、post或等数据传输时,不必停止整个程序,而是切换到其他的线程完成接下来的任务。这样,本质上单线程的python也能实现多线程的效果~
关于多进程和多线程,墙裂推荐廖雪峰的:
进程和线程liaoxuefeng
还有这篇文章:
tonnie:从0到1,python异步编程的演进之路zhuanlan.zhihu
我们以关键词‘pig’为例,可以搜到77张相关图片,然后,让我们来做一下对比测试,比较下原始单线程代码和多线程代码下载速度的差异~
改造前,单线程的代码如下:
#_*_ coding:utf-8 _*_#__author__='阳光流淌007'#__date__2018-01-21'#爬取wallhaven上的的图片,支持自定义搜索关键词,自动爬取并该关键词下所有图片并存入本地电脑。import osimport requestsimport timeimport randomfrom lxml import etreekeyword = input(f{'please input the keywords that you want to download :'})class spider(): #初始化参数 def __init__(self): #headers是请求头,user-agent、accept等字段可通过谷歌chrome浏览器查找! self.headers = { user-agent: mozilla/5.0 (macintosh; intel mac os x 10_12_5) applewebkit/537.36 (khtml, like gecko) chrome/59.0.3071.104 safari/537.36, } #filepath是自定义的,本次程序运行后创建的文件夹路径,存放各种需要下载的对象。 self.filepath = ('/users/zhaoluyang/小python程序集合/桌面壁纸/'+ keyword + '/') def creat_file(self): #新建本地的文件夹路径,用于存储网页、图片等数据! filepath = self.filepath if not os.path.exists(filepath): os.makedirs(filepath) def get_pagenum(self): #用来获取搜索关键词得到的结果总页面数,用totalpagenum记录。由于数字是夹在形如:1,985 wallpapers found for “dog”的string中, #所以需要用个小函数,提取字符串中的数字保存到列表numlist中,再逐个拼接成完整数字。。。 total = url = ((html.text) pageinfo = selector.xpath('//header[@class=listing-header]/h1[1]/text()') string = str(pageinfo[0]) numlist = list(filter(str.isdigit,string)) for item in numlist: total += item totalpagenum = int(total) return totalpagenum def main_fuction(self): #count是总图片数,times是总页面数 self.creat_file() count = self.get_pagenum() print(we have found:{} images!.format(count)) times = int(count/24 + 1) j = 1 start = time.time() for i in range(times): pic_urls = self.getlinks(i+1) start2 = time.time() for item in pic_urls: self.download(item,j) j += 1 end2 = time.time() print('this page cost:',end2 - start2,'s') end = time.time() print('total cost:',end - start,'s') def getlinks(self,number): #此函数可以获取给定numvber的页面中所有图片的链接,用list形式返回 url = ((html.text) pic_linklist = selector.xpath('//a[@class=jsanchor thumb-tags-toggle tagged]/@href') except exception as e: print(repr(e)) return pic_linklist def download(self,url,count): #此函数用于图片下载。其中参数url是形如:(html.text) pageinfo = selector.xpath('//header[@class=listing-header]/h1[1]/text()') string = str(pageinfo[0]) numlist = list(filter(str.isdigit,string)) for item in numlist: total += item totalpagenum = int(total) return totalpagenum def main_fuction(self): #count是总图片数,times是总页面数 self.creat_file() count = self.get_pagenum() print(we have found:{} images!.format(count)) times = int(count/24 + 1) j = 1 start = time.time() for i in range(times): pic_urls = self.getlinks(i+1) start2 = time.time() threads = [] for item in pic_urls: t = thread(target = self.download, args = [item,j]) t.start() threads.append(t) j += 1 for t in threads: t.join() end2 = time.time() print('this page cost:',end2 - start2,'s') end = time.time() print('total cost:',end - start,'s') def getlinks(self,number): #此函数可以获取给定numvber的页面中所有图片的链接,用list形式返回 url = ((html.text) pic_linklist = selector.xpath('//a[@class=jsanchor thumb-tags-toggle tagged]/@href') except exception as e: print(repr(e)) return pic_linklist def download(self,url,count): #此函数用于图片下载。其中参数url是形如:https://alpha.wallhaven.cc/wallpaper/616442/thumbtags的网址 #616442是图片编号,我们需要用strip()得到此编号,然后构造html,html是图片的最终直接下载网址。 string = url.strip('/thumbtags').strip('https://alpha.wallhaven.cc/wallpaper/') html = 'http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-' + string + '.jpg' pic_path = (self.filepath + keyword + str(count) + '.jpg' ) try: start = time.time() pic = requests.get(html,headers = self.headers) f = open(pic_path,'wb') f.write(pic.content) f.close() end = time.time() print(fimage:{count} has been downloaded,cost:,end - start,'s') except exception as e: print(repr(e))spider = spider()spider.main_fuction()
下载77张图片总耗时23.993554830551147 s
对比一下,77张图片的下载时间从157.17s变为23.99s,快了超过6倍。仅仅是简单的改造,多线程对比单线程的提升还是很明显的,其实还可以自己改写多线程算法,还可以加上多进程充分利用cpu数量,还可以用异步协程处理,总之,还有很多可以优化的空间~
东莞分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录