1
import random
import urllib.request

def download_web_image(url):
  name = random.randrange(1, 1000)
  full_name = str(name) + ".jpg"
  urllib.request.urlretrieve(url, full_name)

download_web_image("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg")

What am I doing wrong here?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • A few websites do not allow to download images from there website. There are ways to pretend like a browser. Explore it – kawadhiya21 Jul 03 '21 at 17:16

1 Answers1

0

A more compatible method using the request module would be the following:

import random
import requests

def download_web_image(url):
    name = random.randrange(1, 1000)
    full_name = str(name) + ".jpg"
    r = requests.get(url)
    with open(f'C:\\Test\\{full_name}', 'wb') as outfile:
        outfile.write(r.content)

download_web_image("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg")

Also be sure to modify f'C:\\Test\\{full_name}' to your desired output file path. And be sure to note the imported module changed from import urllib.request to import requests.

Abstract
  • 985
  • 2
  • 8
  • 18