Python使用requests与多线程批量下载图片的完整实现
本文详细介绍如何利用Python的requests模块结合多线程技术,从MySQL数据库中读取图片链接并批量下载至本地。通过封装Spider类、自定义计时器及线程池管理,实现了高效且带有进度统计的图片抓取功能,适用于需要批量处理图像资源的场景。
Python多线程图片下载实现方案
本文主要介绍如何利用Python的requests模块实现图片下载功能,并附带完整的代码示例供参考。
首先,需在MySQL数据库中预先存储已获取的图片链接地址,作为后续下载任务的数据源。
接着,程序将读取数据库中的链接,并利用多线程技术并行将图片文件下载至本地指定目录。
以下是具体的实现代码示例,展示了从数据库读取链接到多线程下载的全过程。
# coding: utf-8
import MySQLdb
import requests
import os
import re
from threading import Thread
import datetime
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/63.0.3239.132 Safari/537.36'}
file_path = 'F:\\mlu2'
if not os.path.exists(file_path):
os.mkdir(file_path)
class Spider(object):
def __init__(self, file_path, header):
self.file_path = file_path
self.header = header
@staticmethod
def timer(func):
def time_count(*args):
start_time = datetime.datetime.now()
func(*args)
end_time = datetime.datetime.now()
day = (end_time - start_time).days
times = (end_time - start_time).seconds
hour = times / 3600
h = times % 3600
minute = h / 60
m = h % 60
second = m
print "爬取完成"
print "一共用时%s天%s时%s分%s秒" % (day, hour, minute, second)
return time_count
def get_link(self):
conn = MySQLdb.connect(host='localhost',
port=3306,
user='root',
passwd='729814',
db='mlu',
charset='utf8')
cur = conn.cursor()
sql = 'select image from msg limit 100' # image为事先爬取存到MySQL的图片链接地址
cur.execute(sql)
img_link = cur.fetchall()
return img_link
def download(self, link):
filename = re.findall(r'.*/(.+)', link)[0]
try:
pic = requests.get(link, headers=self.header)
if pic.status_code == 200:
with open(os.path.join(self.file_path)+os.sep+filename, 'wb') as fp:
fp.write(pic.content)
fp.close()
print "下载完成"
except Exception as e:
print e
@timer
def run_main(self):
threads = []
links = self.get_link()
for link in links:
img = str(link[0])
t = Thread(target=self.download, args=[img])
t.start()
threads.append(t)
for t in threads:
t.join()
spider = Spider(file_path, header)
spider.run_main()
通过对上述代码的分析与测试,可以验证该方法在批量处理图片下载任务时的有效性与效率。
以上就是本文的全部内容,希望这段关于Python利用requests模块下载图片的代码示例能对各位的学习或工作有所帮助,感谢大家的支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













