Python IndexError:使用迭代时列表索引超出范围

时间:2015-08-01 18:12:35

标签: python

我一直试图从App Store下载截图,这是我的代码(我是初学者)。

我遇到的问题是list index out of range at line 60 (screenshotList = data["results"][resultCounter]["screenshotUrls"]

问题是,有时候,搜索API会为使用的搜索字词返回0结果,因此会因为"resultCount" = 0而搞砸了。

我不确定它可能是什么/也不知道如何解决它。有什么帮助吗?

# Required libraries
import urllib
import string
import random
import json
import time

""" screenshotCounter is used so that all screenshots have a different name
resultCounter is used to go from result to result in downloaded JSON file
"""

screenshotCounter = 0
resultCounter = 0

""" Create three random letters as search term on App Store
Download JSON results file
Shows used search term
"""

searchTerm = (''.join(random.choice(string.ascii_lowercase) for i in range(3)))
urllib.urlretrieve("https://itunes.apple.com/search?country=us&entity=software&limit=3&term=" + str(searchTerm), "download.txt")
print "Used search term: " + str(searchTerm)

# Function to download screenshots + give it a name + confirmation msg
def download_screenshot(screenshotLink, screenshotName):
urllib.urlretrieve(screenshotLink, screenshotName)
print "Downloaded with success:" + str(screenshotName)

# Opens newly downloaded JSON file
with open ('download.txt') as data_file:
data = json.load(data_file)

""" Get the first list of screenshots from stored JSON file,
resultCounter = 0 on first iteration
"""
screenshotList = data["results"][resultCounter]["screenshotUrls"]

# Gives the number of found results and serves as iteration limit
iterationLimit = data["resultCount"]

# Prints the number of found results
print str(iterationLimit) + " results found."

""" Change the number of iterations to the number of results, which will be 
different for every request, minus 1 since indexing starts at 0
"""

iterations = [0] * iterationLimit

""" For each iteration (number of results), find each screenshot in the
screenshotList, name it, download it. Then change result to find the next
screenshotList and change screenshotList variable.
"""
for number in iterations:
for screenshotLink in screenshotList:
    screenshotName = "screenshot" + str(screenshotCounter) + ".jpeg"
    download_screenshot(screenshotLink, screenshotName)
    screenshotCounter = screenshotCounter + 1
resultCounter = resultCounter + 1
screenshotList = data["results"][resultCounter]["screenshotUrls"]
# Sleeping to avoid crash
time.sleep(1)

2 个答案:

答案 0 :(得分:0)

我重写了你的代码,以便在尝试任何事情之前检查结果是否存在。如果没有,它将通过循环返回一个新的搜索词。如果有,它将在该迭代结束时停止。

# Required libraries
import urllib
import string
import random
import json
import time

    # Function to download screenshots + give it a name + confirmation msg
def download_screenshot(screenshotLink, screenshotName):
    urllib.urlretrieve(screenshotLink, screenshotName)
    print "Downloaded with success:" + str(screenshotName)

success = False
while success == False: 

    """ Create three random letters as search term on App Store
    Download JSON results file
    Shows used search term
    """

    searchTerm = (''.join(random.choice(string.ascii_lowercase) for i in range(3)))
    urllib.urlretrieve("https://itunes.apple.com/search?country=us&entity=software&limit=3&term=" + str(searchTerm), "download.txt")
    print "Used search term: " + str(searchTerm)



    # Opens newly downloaded JSON file
    with open ('download.txt') as data_file:
        data = json.load(data_file)

    """ Get the first list of screenshots from stored JSON file,
    resultCounter = 0 on first iteration
    """
    resultCount = len(data["results"])
    if  resultCount == 0:
        continue #if no results, skip to the next loop

    success = True
    print str(resultCount) + " results found."

    for j, resultList in enumerate(data["results"]):
        screenshotList = resultList["screenshotUrls"]

        """ For each iteration (number of results), find each screenshot in the
        screenshotList, name it, download it. Then change result to find the next
        screenshotList and change screenshotList variable.
        """
        for i, screenshotLink in enumerate(screenshotList):
            screenshotName = "screenshot" + str(i) + '_' + str(j) + ".jpeg"
            download_screenshot(screenshotLink, screenshotName)
    # Sleeping to avoid crash
    time.sleep(1)

答案 1 :(得分:-1)

你试过吗

try:
    for screenshotLink in screenshotList:
        screenshotName = "screenshot" + str(screenshotCounter) + ".jpeg"
        download_screenshot(screenshotLink, screenshotName)
        screenshotCounter = screenshotCounter + 1
except IndexError:
    pass