简体   繁体   English

如何获取python以从互联网成功下载大图像

[英]How to get python to successfully download large images from the internet

So I've been using 所以我一直在用

urllib.request.urlretrieve(URL, FILENAME)

to download images of the internet. 下载互联网图像。 It works great, but fails on some images. 它的效果很好,但在某些图像上却失败。 The ones it fails on seem to be the larger images- eg. 它失败的原因似乎是较大的图像,例如。 http://i.imgur.com/DEKdmba.jpg . http://i.imgur.com/DEKdmba.jpg It downloads them fine, but when I try to open these files photo viewer gives me the error "windows photo viewer cant open this picture because the file appears to be damaged corrupted or too large". 它可以很好地下载它们,但是当我尝试打开这些文件时,照片查看器显示以下错误:“ Windows照片查看器无法打开此图片,因为该文件似乎已损坏,损坏或太大”。

What might be the reason it can't download these, and how can I fix this? 无法下载这些文件的原因可能是什么,我该如何解决?

EDIT: after looking further, I dont think the problem is large images- it manages to download larger ones. 编辑:进一步查看后,我认为问题不在于大图像-它设法下载更大的图像。 It just seems to be some random ones that it can never download whenever I run the script again. 似乎有些随机的文件,每当我再次运行该脚本时,它便永远无法下载。 Now I'm even more confused 现在我更加困惑

In the past, I have used this code for copying from the internet. 过去,我曾使用此代码从互联网进行复制。 I have had no trouble with large files. 我没有大文件的麻烦。

def download(url):
    file_name = raw_input("Name: ")
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)  
    file_size_dl = 0
    block_size = 8192
    while True:
        buffer = u.read(block_size)
        if not buffer:
            break 

Here's the sample code for Python 3 (tested in Windows 7): 这是Python 3的示例代码(已在Windows 7中测试):

import urllib.request

def download_very_big_image():
    url = 'http://i.imgur.com/DEKdmba.jpg'
    filename = 'C://big_image.jpg'
    conn = urllib.request.urlopen(url)
    output = open(filename, 'wb') #binary flag needed for Windows
    output.write(conn.read())
    output.close()

For completeness sake, here's the equivalent code in Python 2: 为了完整起见,这是Python 2中的等效代码:

import urllib2

def download_very_big_image():
    url = 'http://i.imgur.com/DEKdmba.jpg'
    filename = 'C://big_image.jpg'
    conn = urllib2.urlopen(url)
    output = open(filename, 'wb') #binary flag needed for Windows
    output.write(conn.read())
    output.close()

This should work: use requests module: 这应该工作:使用requests模块:

import requests

img_url = 'http://i.imgur.com/DEKdmba.jpg'
img_name = img_url.split('/')[-1]
img_data = requests.get(img_url).content
with open(img_name, 'wb') as handler:
    handler.write(img_data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM