How To Find the Cast of a Movie Using Python

I am going to walk you through an exciting Python project that fetches movie details, particularly the cast, using the IMDbPY library. If you’re a movie buff like me, this script will be a game-changer in exploring movie details effortlessly. So, let’s dive into it!

Project Overview

The goal of this Python script is to:

  • Take a movie name as input from the user.
  • Search for the movie in the IMDb database.
  • Retrieve and display the cast list (first 10 actors by default).
  • Provide additional movie details such as the release year, rating, and genres.
  • Allow users to select the correct movie if multiple results are found.
  • Offer an option to display the full cast list.

Let’s go step by step through the code to understand how it works and how we can enhance it further.

Explanation

Importing IMDbPY Library

from imdb import IMDb
  • The IMDb class from the IMDbPY library is imported to interact with IMDb’s database.

Function to Get Movie Details

def get_movie_details():
  • Defines a function get_movie_details that will handle fetching and displaying the movie’s details.

Taking User Input

    movie_name = input("Enter the name of the movie: ")
  • The program prompts the user to enter a movie name.

Creating an IMDb Object

    ia = IMDb()
  • Instantiates an IMDb object to interact with IMDb’s API.

Searching for the Movie

    movies = ia.search_movie(movie_name)
  • Uses search_movie() to look up the entered movie name.

Checking if Movie Exists and Allowing Selection

    if not movies:
        print(f"Movie '{movie_name}' not found!")
        return
  • If no matching movie is found, the script informs the user and exits.
  • If multiple movies are found, the user is presented with a selection list.
    print("\nSearch Results:")
    for index, movie in enumerate(movies[:5]):  # Displaying first 5 results
        print(f"{index + 1}. {movie['title']} ({movie.get('year', 'Unknown Year')})")

    choice = input("\nEnter the number of the correct movie (or press Enter to pick the first): ")
    
    if choice.isdigit() and 1 <= int(choice) <= len(movies[:5]):
        movie = movies[int(choice) - 1]
    else:
        movie = movies[0]  # Default to first movie
  • Displays the first five results and allows the user to choose the correct movie.

Fetching and Displaying Movie Details

    ia.update(movie)
    print("\nMovie Details:")
    print(f"Title: {movie.get('title')}")
    print(f"Year: {movie.get('year', 'Unknown')}")
    print(f"Rating: {movie.get('rating', 'No rating available')}")
    print(f"Genres: {', '.join(movie.get('genres', []))}")
  • Retrieves and prints essential details such as title, release year, IMDb rating, and genres.

Fetching and Displaying Cast List

    cast = movie.get('cast', [])
    if cast:
        print("\nMain Cast (Top 10):")
        for actor in cast[:10]:  # Displaying first 10 actors
            print(f"- {actor['name']}")
  • Fetches and prints up to 10 main cast members.

Option to View the Full Cast

        show_full_cast = input("\nDo you want to see the full cast? (yes/no): ").strip().lower()
        if show_full_cast == "yes":
            print("\nFull Cast List:")
            for actor in cast:
                print(f"- {actor['name']}")
    else:
        print("\nNo cast information available.")
  • Asks the user if they want to see the full cast list.

Running the Function

get_movie_details()
  • Calls the function to execute the script.

Example Output

Enter the name of the movie: Titanic

Search Results:
1. Titanic (1997)
2. Titanic (1953)
3. Titanic (1996)
4. Titanic (2012)
5. Titanic (1943)

Enter the number of the correct movie (or press Enter to pick the first): 1

Movie Details:
Title: Titanic
Year: 1997
Rating: 7.9
Genres: Drama, Romance

Main Cast (Top 10):
- Leonardo DiCaprio
- Kate Winslet
- Billy Zane
- Kathy Bates
- Frances Fisher
- Gloria Stuart
- Bill Paxton
- Bernard Hill
- David Warner
- Victor Garber

Do you want to see the full cast? (yes/no): no

Final Thoughts

This enhanced IMDb cast-fetching script improves user interaction by allowing movie selection, displaying IMDb ratings and genres, and offering an option to view the full cast list. It showcases how Python and APIs can fetch real-time data, making it a valuable project for both movie enthusiasts and programmers exploring API integration.

Related blog posts