Downloading a picture via urllib and python

后端 未结 18 1680
离开以前
离开以前 2020-11-22 10:35

So I\'m trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I\'ve found a few similar programs on here that do something simila

18条回答
  •  情书的邮戳
    2020-11-22 10:56

    I have found this answer and I edit that in more reliable way

    def download_photo(self, img_url, filename):
        try:
            image_on_web = urllib.urlopen(img_url)
            if image_on_web.headers.maintype == 'image':
                buf = image_on_web.read()
                path = os.getcwd() + DOWNLOADED_IMAGE_PATH
                file_path = "%s%s" % (path, filename)
                downloaded_image = file(file_path, "wb")
                downloaded_image.write(buf)
                downloaded_image.close()
                image_on_web.close()
            else:
                return False    
        except:
            return False
        return True
    

    From this you never get any other resources or exceptions while downloading.

提交回复
热议问题