我的项目 4:电影搜索应用 (with Python + Streamlit)

发布: (2025年12月3日 GMT+8 06:53)
3 min read
原文: Dev.to

Source: Dev.to

🧱 1. 项目概述

电影搜索应用可以让你:

  • 输入电影标题
  • 获取详细的电影信息
  • 查看海报、类型、剧情简介和评分
  • 使用控制台或 Streamlit 网页界面

📂 2. 项目结构

movie_app/

├── movie_app.py                 # 控制台版本
├── movie_app_streamlit.py       # Streamlit 版本
└── README.md                    #(可选)

🌐 3. 使用的 API:OMDb API

OMDb 需要免费 API 密钥。获取地址:
🔗 https://www.omdbapi.com/apikey.aspx

🖥️ 4. 控制台版本 (movie_app.py)

核心功能

  • 使用 requests 获取电影数据
  • 优雅地处理无效标题
  • 显示关键的电影细节

📌 代码

import requests

API_KEY = "YOUR_API_KEY"  # Put your OMDb API key here

title = input("Movie title: ")

url = f"https://www.omdbapi.com/?t={title}&apikey={API_KEY}"
response = requests.get(url)

if response.status_code != 200:
    print("Error fetching data.")
    exit()

data = response.json()

if data["Response"] == "False":
    print("Movie not found.")
    exit()

print("=== Movie Info ===")
print("Title:", data["Title"])
print("Year:", data["Year"])
print("Genre:", data["Genre"])
print("Plot:", data["Plot"])
print("Rating:", data["imdbRating"])

🌤️ 5. Streamlit 版本 (movie_app_streamlit.py)

新增功能

  • 海报图片展示
  • 格式化良好的输出 UI
  • 错误 / 未找到的处理

📌 代码

import streamlit as st
import requests

st.title("🎬 Sabin's Movie Search App")

API_KEY = "YOUR_API_KEY"

title = st.text_input("Enter movie title:", "Inception")

if st.button("Search"):
    url = f"https://www.omdbapi.com/?t={title}&apikey={API_KEY}"
    response = requests.get(url)

    if response.status_code != 200:
        st.error("Error fetching data.")
    else:
        data = response.json()

        if data["Response"] == "False":
            st.warning("Movie not found.")
        else:
            st.subheader(f"{data['Title']} ({data['Year']})")

            if data["Poster"] != "N/A":
                st.image(data["Poster"], width=300)
            else:
                st.info("No poster available.")

            st.write(f"Genre: {data['Genre']}")
            st.write(f"Rating: ⭐ {data['imdbRating']}")
            st.write(f"Plot: {data['Plot']}")

⚙️ 6. 如何运行

✔ 控制台版本

python3 movie_app.py

✔ Streamlit 版本

pip install streamlit
streamlit run movie_app_streamlit.py

📚 7. 我的收获

  • 使用带认证的 API
  • 处理缺失数据的错误
  • 在 Streamlit 中显示图片
  • CLI 与网页应用的差异

🔧 8. 未来改进

  • 按关键字搜索而非精确标题
  • 展示相似或推荐电影
  • 保存收藏的电影
  • 添加 Rotten Tomatoes / Metacritic 评分
  • 暗色模式 UI
Back to Blog

相关文章

阅读更多 »