怎么在Python中使用requests模块下载图片?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
示例代码:
# 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模块下载图片问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。