Python-image download via url

Any way to download images with python?

I know there is a way with bs4, but I don't know what it is, but I accept any possibility

Url as an example: http://t1.gstatic.com/images?q=tbn:ANd9GcRBL_Z4t3zlPVfo4WLFmVy9CE2zBLph8hmwoexfOQn1kQOHoTDAu9dLCsI4

Author: f4brici0, 2020-04-17

1 answers

There are several ways to do this, see two examples, using distinct libraries.


Using a requests:

import requests

with open('pato.jpg', 'wb') as imagem:
  resposta = requests.get("http://t1.gstatic.com/images?q=tbn:ANd9GcRBL_Z4t3zlPVfo4WLFmVy9CE2zBLph8hmwoexfOQn1kQOHoTDAu9dLCsI4", stream=True)

  if not resposta.ok:
    print("Ocorreu um erro, status:" , resposta.status_code)
  else:
    for dado in resposta.iter_content(1024):
      if not dado:
          break

      imagem.write(dado)

    print("Imagem salva! =)")

See online: https://repl.it/repls/PeriodicDarkgreyLaboratory


Using a urllib:

import urllib.request
import sys

try:
  urllib.request.urlretrieve("http://t1.gstatic.com/images?q=tbn:ANd9GcRBL_Z4t3zlPVfo4WLFmVy9CE2zBLph8hmwoexfOQn1kQOHoTDAu9dLCsI4", "pato.jpg")
  print("Imagem salva! =)")
except:
  erro = sys.exc_info()
  print("Ocorreu um erro:", erro)

See online: https://repl.it/repls/FrigidLovelyLoaderprogram

 1
Author: Daniel Mendes, 2020-04-17 05:12:54