python 多线程下载图片_Python多线程threading—图片下载

上一篇,写了一个爬壁纸图片的小爬虫:Python爬虫入门—图片下载下载效果太慢了,于是乎想到了用多线程改造一下,看看速度能提高多少!

虽然说,由于GIL锁(Global Interpreter Lock)的存在,Python的多线程不是真正意义上的多线程,一个时间段内,一个CPU只能执行一个线程。但是在爬虫相关的程序上,经常出现IO密集型任务多CPU密集型任务少的情况,大多数时间都在等get、post请求、收发数据(对于本次的爬虫图片下载程序,更是如此)。于是可以用Python的多线程来实现加速,即一个线程在get、post或等数据传输时,不必停止整个程序,而是切换到其他的线程完成接下来的任务。这样,本质上单线程的Python也能实现多线程的效果~

关于多进程和多线程,墙裂推荐廖雪峰的:进程和线程​www.liaoxuefeng.com

还有这篇文章:tonnie:从0到1,Python异步编程的演进之路​zhuanlan.zhihu.com

我们以关键词‘pig’为例,可以搜到77张相关图片,然后,让我们来做一下对比测试,比较下原始单线程代码和多线程代码下载速度的差异~

改造前,单线程的代码如下:

#_*_ coding:utf-8 _*_

#__author__='阳光流淌007'

#__date__2018-01-21'

#爬取wallhaven上的的图片,支持自定义搜索关键词,自动爬取并该关键词下所有图片并存入本地电脑。

import os

import requests

import time

import random

from lxml import etree

keyWord = 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 = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc").format(keyWord)

html = requests.get(url)

selector = etree.HTML(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 = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc&page={}").format(keyWord,number)

try:

html = requests.get(url)

selector = etree.HTML(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(f"Image:{count} has been downloaded,cost:",end - start,'s')

except Exception as e:

print(repr(e))

spider = Spider()

spider.main_fuction()

下载77张图片总耗时157.17749691009521 s

引入threading多线程模块后的程序代码如下:

#_*_ coding:utf-8 _*_

#__author__='阳光流淌007'

#__date__='2018-01-28'

#爬取wallhaven上的的图片,支持自定义搜索关键词,自动爬取并该关键词下所有图片并存入本地电脑。

import os

import requests

import time

from lxml import etree

from threading import Thread

keyWord = input(f"{'Please input the keywords that you want to download :'}")

class Spider():

#初始化参数

def __init__(self):

self.headers = {#headers是请求头,"User-Agent"、"Accept"等字段可通过谷歌Chrome浏览器查找!

"User-Agent": "Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1",

}

self.proxies = {#代理ip,当网站限制ip访问时,需要切换访问ip

"http": "http://61.178.238.122:63000",

}

#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 = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc").format(keyWord)

html = requests.get(url,headers = self.headers,proxies = self.proxies)

selector = etree.HTML(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 = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc&page={}").format(keyWord,number)

try:

html = requests.get(url,headers = self.headers,proxies = self.proxies)

selector = etree.HTML(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(f"Image:{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数量,还可以用异步协程处理,总之,还有很多可以优化的空间~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值