Python利用requests模塊下載圖片實例代碼
更新時間:2019年08月12日 09:51:38 作者:傲嬌的草履蟲
這篇文章主要給大家介紹了關于Python利用requests模塊下載圖片的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用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()
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關文章
解決Python 爬蟲URL中存在中文或特殊符號無法請求的問題
今天小編就為大家分享一篇解決Python 爬蟲URL中存在中文或特殊符號無法請求的問題。這種問題,初學者應該都會遇到,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05使用python調(diào)用瀏覽器并打開一個網(wǎng)址的例子
這篇文章主要介紹了使用python調(diào)用瀏覽器并打開一個網(wǎng)址的例子,使用webbrowser模塊實現(xiàn),需要的朋友可以參考下2014-06-06在windows系統(tǒng)中實現(xiàn)python3安裝lxml
本文主要給大家簡單介紹了下在windows以及l(fā)inux系統(tǒng)中使用Python安裝LXML模塊的教程,非常簡單實用,有需要的小伙伴可以參考下2016-03-03