需求:

我爬取的图片是bytes格式,需要直接存到本地。

import urllib3
import os
#pil图像处理标准库
from pil import image
from io import bytesio
http = urllib3.poolmanager()
response = http.request('get','f.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a29f863534d9725bc315d607c8e.jpg')
result = response.data
#将bytes结果转化为字节流
bytes_stream = bytesio(result)
#读取到图片
roiimg = image.open(bytes_stream)
# roiimg.show() #展示图片
#print(type(result))
#print(response.status)
imgbytearr = bytesio() #初始化一个空字节流
roiimg.save(imgbytearr,format('png'))  #把我们得图片以‘png'保存到空字节流
imgbytearr = imgbytearr.getvalue() #无视指针,获取全部内容,类型由io流变成bytes。
# dir_name = os.mkdir('baiduimg')
img_name = '1.jpg'
with open(os.path.join('baiduimg',img_name),'wb') as f:
 f.write(imgbytearr)

补充:python3保存请求中的byte图片流到本地

def getimage():
 datestr = gettimestamp()
 imageurl = "xxxxxurl"
 verifytext = requests.get(imageurl,verify=false).content
 print(verifytext)
 return verifytext 
def gettimestamp():
 timestamp = str(time.time())
 timestamp = timestamp.replace(".", "")[0:13]
 return int(timestamp) 
def startebloginsystem(username,password): 
 for i in range(1,100):
  result = getimage()
  img_name = str(i)+'.jpg'
  path = "e:/yzmimages/" + img_name
  with open(path, 'wb') as f:
   f.write(result)

方法一,使用urllib.urlretrieve()

import urllib 
# 网络上图片的地址
img_src = 'https://www.baidu.com/img/bd_logo1.png?where=super'
# 将图片下载到本地
urllib.urlretrieve(img_src,'d:/images/1.jpg')

方法二,使用pil+requests:

import requests
from pil import image
from io import bytesio 
response = requests.get(img_src)
image = image.open(bytesio(response.content))
image.save('d:/images/1.jpg')

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。