Python - Saving an image from a url [duplicate]


import urllib  
urllib.urlretrieve('url', 'filename')  

import os  
import urllib  
import urllib2  
from bs4 import BeautifulSoup

url = ""  
html = urllib2.urlopen(url)  
soup = BeautifulSoup(html)

imgs = soup.findAll("div", {"class":"thumb-pic"})  
for img in imgs:  
        imgUrl = img.a['href'].split("imgurl=")[1]
        urllib.urlretrieve(imgUrl, os.path.basename(imgUrl))

Python 2

Here is a more straightforward way if all you want to do is save it as a file:

import urllib

urllib.urlretrieve("", "local-filename.jpg")

The second argument is the local path where the file should be saved.

Python 3

As SergO suggested the code below should work with Python 3.

import urllib.request

urllib.request.urlretrieve("", "local-filename.jpg")