json 如何使用python打印www.example.com上排名前50的电影的原标题themoviedatabase.org?

x7rlezfr  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(103)

hello all i'm learning python recently and i need to analyze the web of themoviedb.org website. I want to extract all the movies in the database and I want to print the original title of the first 50 movies.This is a piece of the json file that i receive as a response following my network request:

{"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部电影的原片名?

y4ekin9u

y4ekin9u1#

正确格式化您发布的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_tileresults中每个字典/Map的一部分。

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

应该行得通。

相关问题