python save image from url

前端 未结 9 1167
滥情空心
滥情空心 2020-12-04 09:41

I got a problem when I am using python to save an image from url either by urllib2 request or urllib.urlretrieve. That is the url of the image is valid. I could download it

相关标签:
9条回答
  • 2020-12-04 10:32

    It is the simplest way to download and save the image from internet using urlib.request package.

    Here, you can simply pass the image URL(from where you want to download and save the image) and directory(where you want to save the download image locally, and give the image name with .jpg or .png) Here I given "local-filename.jpg" replace with this.

    Python 3

    import urllib.request
    imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"
    
    urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")
    

    You can download multiple images as well if you have all the image URLs from the internet. Just pass those image URLs in for loop, and the code automatically download the images from the internet.

    0 讨论(0)
  • 2020-12-04 10:33

    Python code snippet to download a file from an url and save with its name

    import requests
    
    url = 'http://google.com/favicon.ico'
    filename = url.split('/')[-1]
    r = requests.get(url, allow_redirects=True)
    open(filename, 'wb').write(r.content)
    
    0 讨论(0)
  • 2020-12-04 10:37

    A sample code that works for me on Windows:

    import requests
    
    with open('pic1.jpg', 'wb') as handle:
            response = requests.get(pic_url, stream=True)
    
            if not response.ok:
                print response
    
            for block in response.iter_content(1024):
                if not block:
                    break
    
                handle.write(block)
    
    0 讨论(0)
提交回复
热议问题