【问题标题】:Why does this image-download-script not work?为什么这个图像下载脚本不起作用?
【发布时间】:2014-08-05 02:24:32
【问题描述】:

我有一个代码和一个问题。

import string
import random
import httplib
import urllib
import os
import sys
import inspect

def id_generator(size=5, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


picnumber = raw_input('Please enter the amount of images you want!')
nothingfoundnumber=0
foundnummer=0

scriptpath = os.path.dirname(sys.argv[0])
filename = scriptpath + "/output/"
if not os.path.exists(os.path.dirname(filename)):
    os.makedirs(os.path.dirname(filename))


while foundnummer != picnumber:
    randompicstring = id_generator()
    print "Trying " + str(randompicstring)
    try:
        urllib.urlretrieve("http://i.imgur.com/" +randompicstring+ ".gif", "/test/" +randompicstring + ".gif")
        foundnummer+=1
        print str(randompicstring) + "was found! Makes " +str(foundnummer)+ " out of " +str(picnumber)+"!"
    except IOError:
        nothingfoundnumber+=1
        print str(randompicstring) + "not found. It was the "+str(nothingfoundnumber)+" try."

这样做的目的是尝试随机组合 asciiletters 和数字以在 imgur.com 上查找图像(例如http://i.imgur.com/XgEVx.png)。如果它发现了一些东西,它应该说并保存图像并增加 foundnumber。如果它没有找到图像,它应该这样说并增加 nothingfoundnumber。

现在它不起作用,它只是说它总是找到一些东西并且什么都不保存。 有人可以帮我解决这个问题吗?

【问题讨论】:

标签: python image download urllib


【解决方案1】:

您还应该考虑使用Imgur API 而不是生成随机字符串。看起来有一个随机图像的端点。

【讨论】:

    【解决方案2】:

    这可能是因为urlretrieve 在发生错误 404 时没有引发异常。您可以在urlretrieve 之前尝试urlopen,看看这是否是404:

    randompicstring = id_generator()
    print "Trying " + str(randompicstring)
    url = "http://i.imgur.com/" +randompicstring+ ".gif"
    
    res = urllib.urlopen(url) # test url
    if res.getcode() == 200: # valid link
        try:
            urllib.urlretrieve(url, "/test/" +randompicstring + ".gif") # download
            foundnummer+=1
            print str(randompicstring) + "was found! Makes " +str(foundnummer)+ " out of " +str(picnumber)+"!"
        except IOError:
            print "IOError..."
    else: # invalid link
        nothingfoundnumber+=1
        print str(randompicstring) + "not found. It was the "+str(nothingfoundnumber)+" try."
    

    【讨论】:

    • 谢谢,但它仍然无法正常工作。示例输出:mxNDlwas found! Makes 76 out of 10! Trying NfUsn NfUsnwas found! Makes 77 out of 10! Trying jVF0e 仍然没有保存图像。
    • 看起来即使图片不存在,imgur 也会返回200 代码......在这种情况下,我认为@chrisb 有正确的答案:你应该使用 Imgur API!跨度>
    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 2020-12-14
    • 2013-10-20
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多