list index out of range with youtube-search module

Viewed 359

i've tried out python module called "Youtube-search" and here's the little code to get a link of the first video

from youtube_search import YoutubeSearch

results = YoutubeSearch('Sabaton', max_results=10).to_dict()
dictionary = results[0]
print(f"youtube.com{dictionary.get('link')}")

the search term ("Sabaton") was always the same sometimes it gave me the link like it should have but sometimes it throws this error at me

dictionary = results[0]
IndexError: list index out of range

i dont know why it's giving me this error sometimes, considering as mentioned above the search terms didnt change and they were all made in a short period of time so there was no chance that a new video was uploaded with tag "Sabaton"

1 Answers

The YouTube search API (which you are using via the youtube-search Python module) can return slightly different results when queried multiple times. If and when the returned results is an empty list, e.g. [], attempting to index into this list with an index of 0 will result in an IndexError.

To make your code a bit more robust, you could check if there are any results before attempting to index into the list, e.g.:

from youtube_search import YoutubeSearch

results = YoutubeSearch('Sabaton', max_results=10).to_dict()
if len(results) > 0:
    dictionary = results[0]
    print(f"youtube.com{dictionary.get('link')}")
else:
    print("No results found.")
Related