Python利用requests模块下载图片实例代码

yipeiwu_com5年前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设计】的支持。

相关文章

Python实现把json格式转换成文本或sql文件

python如何将json格式的数据快速的转化成指定格式的数据呢?或者转换成sql文件? 下面的例子是将json格式的数据准换成以#_#分割的文本数据,也可用于生成sql文件。 [r...

对numpy中二进制格式的数据存储与读取方法详解

对numpy中二进制格式的数据存储与读取方法详解

使用save可以实现对numpy数据的磁盘存储,存储的方式是二进制。查看使用说明,说明专门提到了是未经压缩的二进制形式。存储后的数据可以进行加载或者读取,通过使用load方法。 In...

Python3 正在毁灭 Python的原因分析

Python 3毫不费力地成为发生在Python社区里最糟糕的事。我还记得第一次使用Python的时候,我还在花大量时间在C++这块上,而Python就像是我的一次开光。我可以打开文本编...

Python深入学习之对象的属性

Python一切皆对象(object),每个对象都可能有多个属性(attribute)。Python的属性有一套统一的管理方案。 属性的__dict__系统 对象的属性可能来自于其类定义...

Anaconda下安装mysql-python的包实例

Anaconda下安装mysql-python的包实例

Anaconda下需要使用Python与MySQL数据库进行交互,所以需要import一个mysql-python的包, 但是在ipython中引用的时候发现Anaconda并没有包含该...