python从url保存图像 [英] python save image from url

查看:859
本文介绍了python从url保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用python通过urllib2 request或urllib.urlretrieve从url保存图像时出现问题。这是图像的网址是有效的。我可以使用资源管理器手动下载它。但是,当我使用python下载图像时,无法打开该文件。我使用Mac OS预览来查看图像。谢谢!

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 manually using the explorer. However, when I use python to download the image, the file cannot be opened. I use Mac OS preview to view the image. Thank you!

更新:

代码如下

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())

我想下载的图片网址是
http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

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

此网址有效我可以通过浏览器保存它,但python代码将下载无法打开的文件。预览说它可能已损坏或使用预览无法识别的文件格式。
我比较了我用Python下载的图像和我通过浏览器手动下载的图像。前者的大小要小几个字节。所以似乎文件未完成,但我不知道为什么python无法完全下载它。

This URL is valid and I can save it through the browser but the python code would download a file that cannot be opened. The Preview says "It may be damaged or use a file format that Preview doesn't recognize." I compare the image that I download by Python and the one that I download manually through the browser. The size of the former one is several byte smaller. So it seems that the file is uncompleted, but I don't know why python cannot completely download it.

推荐答案

示例代码这对我在Windows上有用:

A sample code that works for me on Windows:

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)

这篇关于python从url保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆