需求:
我爬取的图片是bytes格式,需要直接存到本地。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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图片流到本地
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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()
1
2
3
4
5
|
import urllib # 网络上图片的地址 img_src = 'https://www.baidu.com/img/bd_logo1.png?where=super' # 将图片下载到本地 urllib.urlretrieve(img_src, 'D:/images/1.jpg' ) |
方法二,使用PIL+requests:
1
2
3
4
5
6
|
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' ) |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/wgPython/article/details/80740067