pythonexceptioninformation-retrievalimdbimdbpy

how handle exception using IMDBPY


this code works perfect with movie Id that has plot keyword .

from imdb import IMDb
ia = IMDb()
black_panther = ia.get_movie('1825683', info='keywords')
print(black_panther['keywords'])

bur for movies that haven't plot keyword like this id(5950092) it returns exception.any idea for handle exception?


Solution

  • Since imdb.Movie.Movie is a subclass of imdb.utils._Container with a get method similar to that of a dict, and which docstring reads:

    >>> imdb.utils._Container.get.__doc__
    "Return the given section, or default if it's not found."
    

    That means you can do this to never throw an exception if there are no keywords:

    movie = ia.get_movie('5950092', info='keywords')
    
    movie.get('keywords', [])
    # Result: [], empty list
    

    You can also work with an Exception if you want to:

    try:
        keywords = movie['keywords']
    except KeyError:
        keywords = []