Skip to content Skip to sidebar Skip to footer

Temporarily Retrieve An Image Using The Requests Library

I'm writing a web scraper than needs to scrape only the thumbnail of an image from the url. This is my function using, the urlib library. def create_thumb(self): if self.url an

Solution 1:

You could skip saving to a temporary file part and use the corresponding response object directly to create the image:

#!/usr/bin/env python3import urllib.request
from PIL import Image # $ pip install pillow

im = Image.open(urllib.request.urlopen(url))
print(im.format, im.mode, im.size)

Here's requests analog:

#!/usr/bin/env pythonimport requests # $ pip install requestsfrom PIL import Image # $ pip install pillow

r = requests.get(url, stream=True)
r.raw.decode_content = True# handle spurious Content-Encoding
im = Image.open(r.raw)
print(im.format, im.mode, im.size)

I've tested it with Pillow 2.9.0 and requests 2.7.0. It should work since Pillow 2.8.

Solution 2:

You can write to a io.BytesIO:

import requests

from PIL import Image
from io import BytesIO

r = requests.get(self.url)
b = BytesIO(r.content)
size = 350, 350
img = Image.open(b)
img.thumbnail(size)
img.save("foo.thumbnail", "JPEG")

Post a Comment for "Temporarily Retrieve An Image Using The Requests Library"