Python 为什么这个图像下载脚本不起作用?
我有一个密码和一个问题Python 为什么这个图像下载脚本不起作用?,python,image,download,urllib,Python,Image,Download,Urllib,我有一个密码和一个问题 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
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."
这样做的目的是尝试将ascilletter和数字随机组合,以便在imgur.com上找到图像(例如)。如果它发现了什么,它应该说,并保存图像,增加foundnumber。如果找不到图像,它应该这样说,并增加nothingfoundnumber
现在它不起作用了,它只是说它总是能找到一些东西,却什么也不保存。
有人能帮我解决这个问题吗?这可能是因为发生错误404时,
urlretrieve
不会引发异常。您可以在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."
您可能还应该考虑使用而不是生成随机字符串。看起来随机图像有一个端点。url retrieve返回一个元组(文件名,httplib.HTTPMessage实例)。你的404在后者。请看,谢谢,但还是不行。示例输出:
MXNDL已找到!10分中有76分!正在尝试找到NfUsn NfUsn!十分之七十七!正在尝试jVF0e
仍没有保存图像。即使图像不存在,imgur似乎也会返回200
代码。。。在这种情况下,我认为@chrisb有正确的答案:您应该使用imgurapi!