Python - image download via url

Asked

Viewed 1,666 times

0

  • Need to be with bs4? What exactly do you want to do? Just download an image you have the link or parse the HTML and download all images?

  • no, it doesn’t have to be by bs4

1 answer

1


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


Using the 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 the 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

    thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.