问题描述
- python3.5 用socket提取图片报错,急!
-
我在学习Python for Information 这本书,第12章是用socket去抓取一张网络图片,但是报错UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 246: invalid start byte用python 2.7是可以正常用的,但是python3.5 在 这句报错
picture = picture + bytes.decode(data)
请大神指点下解决方法
import socket import time mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) s = 'GET http://www.py4inf.com/cover.jpg HTTP/1.0nn' mysock.send(str.encode(s)) count = 0 picture = '' while True: data = mysock.recv(5120) if (len(data) < 1): break #time.sleep(0.25) count = count + len(data) print(len(data), count) picture = picture + bytes.decode(data) mysock.close() # Look for the end of header pos = picture.find('rnrn') print('Header length', pos) print(picture[:pos]) # Skip past the header and save the picture data picture = picture[pos+4:] fhand = open('stuff.jpg', 'wb') fhand.write(picture) fhand.close()
解决方案
PYTHON3以后,字符串默认就是unicode字符集了。不需要decode
解决方案二:
字符集出现问题,不过我也没用3.0.....
时间: 2024-10-05 15:52:42