如何用python打印themoviedatabase.org中排名前50的电影的原始标题?

问题描述 投票:0回答:2

大家好,我最近正在学习 python,我需要分析 themoviedb.org 网站的网络。我想要提取数据库中的所有电影,并且想要打印前 50 部电影的原始标题。这是我在网络请求之后作为响应收到的 json 文件的一部分:

{"page":1,"results":[{"adult":false,"backdrop_path":"/5gPQKfFJnl8d1edbkOzKONo4mnr.jpg","genre_ids":[878,12,28],"id":76600,"original_language":"en","original_title":"Avatar: The Way of Water","overview":"Set more than a decade after the events of the first film, learn the story of the Sully family (Jake, Neytiri, and their kids), the trouble that follows them, the lengths they go to keep each other safe, the battles they fight to stay alive, and the tragedies they endure.","popularity":5332.225,"poster_path":"/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg","release_date":"2022-12-14","title":"Avatar: The Way of Water","video":false,"vote_average":7.7,"vote_count":3497},{......}],"total_pages":36589,"total_results":731777}

这是我的代码:

import requests

response = requests.get("https://api.themoviedb.org/3/discover/movie?api_key=my_key&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_watch_monetization_types=flatrate")
jsonresponse=response.json()
page=jsonresponse["page"]
results=jsonresponse["results"]
for i in range(50):
  for result in jsonresponse["original_title"][i]:
        print(result)

我的代码不起作用。错误:“KeyError:'original_title'”。如何打印前 50 部电影的原片名?

python json for-loop themoviedb-api
2个回答
1
投票

正确格式化您发布的 json 时:

{
    "page": 1,
    "results": [
        {
            "adult": false,
            "backdrop_path": "/5gPQKfFJnl8d1edbkOzKONo4mnr.jpg",
            "genre_ids": [
                878,
                12,
                28
            ],
            "id": 76600,
            "original_language": "en",
            "original_title": "Avatar: The Way of Water",
            "overview": "Set more than a decade after the events of the first film, learn the story of the Sully family (Jake, Neytiri, and their kids), the trouble that follows them, the lengths they go to keep each other safe, the battles they fight to stay alive, and the tragedies they endure.",
            "popularity": 5332.225,
            "poster_path": "/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg",
            "release_date": "2022-12-14",
            "title": "Avatar: The Way of Water",
            "video": false,
            "vote_average": 7.7,
            "vote_count": 3497
        },
        {
         ....
        }
    ],
    "total_pages": 36589,
    "total_results": 731777
}

人们可以很容易地看到

original_tile
results
中每个字典/地图的一部分。所以使用

for result in results:
  print(result["original_title"])

应该可以。


0
投票

还有上面未列出的进口产品吗? Python 是哪个版本? 3.10? 没有足够的信息来运行此代码。我相信必须安装 Django 才能使用 jsonresponse。我有类似的需求,因此需要功能副本。

© www.soinside.com 2019 - 2024. All rights reserved.