簡體   English   中英

Python IndexError:使用迭代時列表索引超出范圍

[英]Python IndexError: list index out of range when using iterations

我一直在嘗試從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)

我重寫了您的代碼,以嘗試任何結果之前檢查結果是否存在。 如果沒有,它將以新的搜索詞返回循環。 如果存在,它將在該迭代結束時停止。

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM