i’m trying to search songs based on song titles and artists names from youtube and trying to get the link of the 1st video that appeared in the search queue and download the video, but i’m facing this error. Can u help me to fix this error ?
This is how I tried to implement…..
import re import urllib.request import urllib.parse i=0 for a in artists: for t in titles: input = urllib.parse.urlencode({'search_query': titles[i] + ' by ' + artists[i]}) #html = requests.get("https://www.youtube.com/results?search_query=" + s_k) html = urllib.request.urlopen("http://www.youtube.com/results?" + input) video_ids = re.findall(r'href="/watch?v=(.{11})', html.read().decode()) print("https://www.youtube.com/watch?v=" + video_ids[0]) i+=1 if i == 809: break
[here, ‘titles’ is a list of song titles and ‘artists’ is a list of artists. and 809 is the length of both lists]
Advertisement
Answer
This error means that the video_ids list is empty since its first index, namely 0, is out of range. You could wrap it in a try except block:
try: print("https://www.youtube.com/watch?v=" + video_ids[0]) except IndexError: pass