1

Я пытаюсь скачать изображение из интернета и записать его в файл:

#!/usr/bin/env python3

import urllib.request
from PIL import Image

class WebConn:

    def __init__(self, url):
        self.url = url

    def __enter__(self):
        self.logo = urllib.request.urlopen(url)
        return self.logo

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')

if __name__ == '__main__':
    url = 'http://www.google.com/images/srpr/logo3w.png'
    file_name = 'image.jpg'

    with WebConn(url) as im:
        f = open(file_name, "wb")
        f.write(im)
        f.close()

        img = Image.open('./' + file_name)
        img.show()   

Однако получаю следующее сообщение об ошибке:

Traceback (most recent call last):
  File "./hello.py", line 24, in <module>
    f.write(im) TypeError: a bytes-like object is required, not 'HTTPResponse'

Помогите пожалуйста исправить скрипт.

LIVE DEMO здесь

1
  • Вопрос абсолютно не соответствует заголовку. При чём здесь blob вообще? 12 фев 2019 в 4:20

1 ответ 1

2

Попробуйте так:

import requests
from PIL import Image

def download_pic(url, filename, chunk_size=1024):
    r = requests.get(url, stream=True)
    if r.ok:
        with open(filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size):
                f.write(chunk)

Проверка:

In [34]: filename = r'c:/temp/logo.png'

In [35]: download_pic(url, filename)

In [36]: img = Image.open(filename)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.