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.0\n\n'
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('\r\n\r\n')
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()

查看全部
hetianbiao
脑力民工
2016/02/04 06:24
  • codec
  • python
  • 图片
  • 网络
  • socket
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复