Python save image from url

I'm having a problem when I use python to save an image from a URL, either using a urllib2 request or urllib.urlretrieve. That is, the image URL is valid. I can download it manually using explorer. However, when I use python to upload an image, the file cannot be opened. I am using Mac OS preview to view the image. Thanks!

UPDATE:

The code is as follows

def downloadImage(self): request = urllib2.Request(self.url) pic = urllib2.urlopen(request) print "downloading: " + self.url print self.fileName filePath = localSaveRoot + self.catalog + self.fileName + Picture.postfix # urllib.urlretrieve(self.url, filePath) with open(filePath, 'wb') as localFile: localFile.write(pic.read()) 

The URL of the image I want to download is http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

This url is valid and I can save it through a browser, but python code will load a file that cannot be opened. The preview says: "It may be corrupted or use a file format that Preview does not recognize." I am comparing an image that I upload using Python and one that I upload manually through a browser. The size of the first is a few bytes smaller. Thus, it seems that the file is not complete, but I do not know why python cannot load it completely.

+23
source share
6 answers

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) 
+36
source
 import requests img_data = requests.get(image_url).content with open('image_name.jpg', 'wb') as handler: handler.write(img_data) 
+46
source

A snippet of Python code to download a file with a URL and save it 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) 
+6
source
 import random import urllib.request def download_image(url): name = random.randrange(1,100) fullname = str(name)+".jpg" urllib.request.urlretrieve(url,fullname) download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg") 
+2
source
 import urllib.request import os img_url = "https://betanews.com/wp-content/uploads/2017/09/firefox-logo.jpg" img_name = os.path.basename(img_url) urllib.request.urlretrieve(img_url,img_name) 
+1
source

For Linux in the case; You can use the Wget command

 import os url1 = 'YOUR_URL_WHATEVER' os.system('wget {}'.format(url1)) 
0
source

All Articles