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:
print (info.decode(('utf-8')))
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.
Don't use Unicode transformations for JPG images.
Unicode is for text. What you are downloading is not text, it is something else.
Try this:
Or, more simply:
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