【问题标题】:My code gives me an error: 'list index out of range'我的代码给了我一个错误:“列表索引超出范围”
【发布时间】:2020-10-14 18:57:14
【问题描述】:

有时当我运行代码时,它会给出正确的输出,有时它会显示“列表索引超出范围”,有时它只是继续跟随代码。我在以下位置找到了代码:https://www.codeproject.com/articles/873060/python-search-youtube-for-video

我该如何解决这个问题?

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

【问题讨论】:

  • 做一个print(search_results) 看看你是否真的有任何结果。如果没有,则search_results[0] 将抛出该错误。
  • 如果您现在正在使用 IDE,那么现在正是学习其调试功能的好时机——例如设置断点和检查值。或者你可以花点时间熟悉一下内置的Python debugger。此外,在程序的关键点打印 stuff 可以帮助您跟踪正在发生或未发生的事情。 How to debug small programs

标签: python error-handling youtube imdb omdbapi


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    当没有得到“搜索结果”时发生错误,导致无法找到search_results[0]。

    我建议您使用“if/else”语句,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多