本文主要介绍的是关于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()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python利用requests模块下载图片实例代码”评论...
更新日志
2024年10月07日
2024年10月07日
- 群星《前途海量 电影原声专辑》[FLAC/分轨][227.78MB]
- 张信哲.1992-知道新曲与精丫巨石】【WAV+CUE】
- 王翠玲.1995-ANGEL【新艺宝】【WAV+CUE】
- 景冈山.1996-我的眼里只有你【大地唱片】【WAV+CUE】
- 群星《八戒 电影原声带》[320K/MP3][188.97MB]
- 群星《我的阿勒泰 影视原声带》[320K/MP3][139.47MB]
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]