1

有时当我运行代码时,它会给我正确的输出,有时它会说“列表索引超出范围”,有时它只是继续跟随代码。我在以下位置找到了代码: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()
4

2 回答 2

1

未获得“搜索结果”时会发生错误,因此无法找到 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])
于 2020-06-24T13:45:55.163 回答
0

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")
于 2020-06-24T13:47:21.330 回答