1

Sometimes when I run the code it gives me the correct output, other times it says "List index out of range" and other times it just continues following code. I found the code on: https://www.codeproject.com/articles/873060/python-search-youtube-for-video

How can I fix this?

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()
halfer
  • 19,824
  • 17
  • 99
  • 186
ICH_python
  • 51
  • 1
  • 1
  • 5
  • 2
    Do a `print(search_results)` and see if you actually have any results. If there aren't any, then `search_results[0]` will throw that error. – 0buz Jun 24 '20 at 13:37
  • If you are using an IDE now is a good time to learn its debugging features - like setting breakpoints and examining values. Or you could spend a little time and get familiar with the built-in [Python debugger](https://docs.python.org/3/library/pdb.html). Also, printing *stuff* at strategic points in your program can help you trace what is or isn't happening. [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – wwii Jun 24 '20 at 14:01

2 Answers2

1

The error occurs when no 'search results' have been obtained, such that search_results[0] cannot be found.

I would suggest you use an 'if/else' statement, something like:

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])
Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
0

search[0] will return the first element of the list. However, if there are no elements in the list, there will not be a first element in the list, and "List index out of range". I recommend adding an if statement to check if the length of search_results is greater than 0 and then printing search[0]. Hope this helps!

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