UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节 [英] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

查看:116
本文介绍了UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从链接中抓取图片并将其放入图像文件中.请求响应正在返回字节流.因此,我正在使用解码('utf-8')转换为Unicode流,但是,我遇到了以下错误:

I am trying to scrap a picture from the link and put it into a image file. The request response is returning a byte stream. So I am using decode('utf-8') to convert to unicode stream however, I am facing the following error:

打印(info.decode(('utf-8')))

print (info.decode(('utf-8')))

UnicodeDecodeError:'utf-8'编解码器无法解码位置0:无效的起始字节中的字节0xff

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    from urllib import request
    img = request.urlopen('http://www.py4inf.com/cover.jpg')
    fhand = open('cover.jpg', 'w')
    size = 0
    while True:
        info = img.read(100000)
        if len(info) < 1 : break
        size = size + len(info)
        print (info.decode(('utf-8')))
        fhand.write(info.decode(('utf-8')))

    print (size,'characters copied.')
    fhand.close()

请让我知道如何进行.谢谢.

Please let me know how can I proceed. Thanks.

推荐答案

应该以二进制模式打开文件,然后可以逐字节复制流.由于shutil已经具有便捷的帮助程序实用程序,因此您可以

The file should be opened in binary mode and then you can copy the stream byte for byte. Since shutil already has a handy helper utility, you can

import shutil
import os
from urllib import request

img = request.urlopen('http://www.py4inf.com/cover.jpg')
with open('cover.jpg', 'wb') as fhand:
    shutil.copyfileobj(img, fhand)
print(os.stat('cover.jpg').st_size, 'characters copied')

这篇关于UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆