Python索引器错误:使用迭代时列表索引超出范围

2024-09-30 04:34:08 发布

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

我一直在尝试从appstore下载截图,下面是我的代码(我是初学者)。在

我遇到的问题是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)

Tags: ofthetoinimportnumberdatadownload
2条回答

在尝试任何操作之前,我重写了您的代码以检查是否存在结果。如果没有,它将返回到循环中,并返回一个新的搜索词。如果有,它将在迭代结束时停止。在

# 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)

你试过了吗

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

相关问题 更多 >

    热门问题