您好,登錄后才能下訂單哦!
怎么在Python中使用requests模塊下載圖片?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
示例代碼:
# 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 "一共用時(shí)%s天%s時(shí)%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()
關(guān)于怎么在Python中使用requests模塊下載圖片問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。