Python 我的代码给了我一个错误:';列表索引超出范围';

Python 我的代码给了我一个错误:';列表索引超出范围';,python,error-handling,youtube,imdb,omdbapi,Python,Error Handling,Youtube,Imdb,Omdbapi,有时当我运行代码时,它会给我正确的输出,有时它会说“列表索引超出范围”,有时它只是继续执行代码。我在以下位置找到代码: 我怎样才能解决这个问题 searchM = input("Enter the movie you would like to search: ") def watch_trailer(): query_string = urllib.parse.urlencode({"search_query" : searchM})

有时当我运行代码时,它会给我正确的输出,有时它会说“列表索引超出范围”,有时它只是继续执行代码。我在以下位置找到代码:

我怎样才能解决这个问题

searchM = input("Enter the movie you would like to search: ")

def watch_trailer():
    query_string = urllib.parse.urlencode({"search_query" : searchM})
    html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
    search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
    print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0])
    
watch_trailer()

当未获得“搜索结果”时,会发生此错误,因此无法找到搜索结果[0]

我建议您使用“如果/其他”语句,例如:

if len(search_results) == 0:
    print("No search results obtained. Please try again.")
else:
     print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0])

搜索[0]将返回列表的第一个元素。但是,如果列表中没有元素,则列表中不会有第一个元素,并且“列表索引超出范围”。我建议添加一个if语句来检查搜索结果的长度是否大于0,然后打印搜索[0]。希望这有帮助

if len(search_results) > 0:
    print(search_results[0])
else:
    print("There are no results for this search")

打印(搜索结果),看看你是否真的有任何结果。如果没有,则
搜索结果[0]
将抛出该错误。如果您现在正在使用IDE,则是学习其调试功能的好时机,如设置断点和检查值。或者你可以花一点时间熟悉内置的。此外,在程序的关键点打印内容可以帮助您跟踪正在发生或未发生的事情。