如何使用 IMDBPY 处理异常

how handle exception using IMDBPY

此代码与具有 plot 关键字的电影 ID 完美配合。

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

bur 对于没有像这个 id (5950092) 这样的 plot 关键字的电影它 returns exception.any 处理异常的想法?

在 IMDbPY 中,Movie 实例的行为类似于字典,因此您以通常的方式处理异常(使用 try/except 子句)。参见 https://docs.python.org/3/tutorial/errors.html#handling-exceptions

作为类似字典的对象,您还可以使用 'keywords' in black_panther 测试键的存在并获取值而不引发 n 异常,但如果键丢失则返回 None,使用black_panther.get('keywords').

因为 imdb.Movie.Movieimdb.utils._Container 的子类,具有类似于 that of a dictget 方法,并且文档字符串为:

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

这意味着如果没有关键字,您可以这样做永远不会抛出异常:

movie = ia.get_movie('5950092', info='keywords')

movie.get('keywords', [])
# Result: [], empty list

如果您愿意,也可以使用 Exception

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