为什么这个imagedownloadscript不起作用?

2024-04-28 21:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个密码和一个问题。你知道吗

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."

这样做的目的是尝试随机组合的腹水和数字,以找到图像上imgur.com(例如http://i.imgur.com/XgEVx.png)。如果它发现了什么,它应该说,并保存图像和增加foundnumber。如果它没有找到一个图像,它应该这样说,并增加nothingfoundnumber。你知道吗

现在它不起作用,它只是说它总是找到一些东西,什么也不保存。 有人能帮我修一下吗?你知道吗


Tags: path图像importcomstringosfilenameprint
2条回答

这可能是因为发生错误404时urlretrieve不会引发异常。您可以尝试在urlopen之前urlretrieve查看这是否是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."

您可能还应该考虑使用Imgur API,而不是生成随机字符串。看起来随机图像有一个端点。你知道吗

相关问题 更多 >