You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用IMDbPY抓取电影摄影师数据时如何处理None对象的TypeError报错

问题原因

报错触发在cinematographer = movie.get('cinematographers')[0]这行,当你遍历的电影ID没有对应的「摄影师」字段数据时,movie.get('cinematographers')会返回None,直接对None执行下标取值[0]就会抛出TypeError。

解决方案

核心是先判断cinematographers字段的返回值是否为非空列表,再执行后续的取值操作,修改后可正常运行的代码如下:

from imdb import IMDb, IMDbError
ia = IMDb() 
doplist = []

items = ["0050083", "6273736", "2582802"]

def imdblistdop(myList=[], *args):
    for x in myList:
        # 捕获获取电影数据可能出现的接口异常
        try:
            movie = ia.get_movie(x)
        except IMDbError as e:
            print(f"获取电影ID{x}数据失败:{e}")
            # 可根据需求调整占位值,不需要存储异常数据也可以直接continue跳过
            doplist.append("获取失败")
            continue
        # 取摄影师字段时默认返回空列表,避免拿到None
        cinematographers = movie.get('cinematographers', [])
        # 非空判断,列表有内容才执行后续取值逻辑
        if not cinematographers:
            print(f"电影ID{x}无摄影师数据")
            doplist.append("无摄影师数据")
            continue
        cinematographer = cinematographers[0]
        print(cinematographer)
        print(doplist)
        try:
            itemdop = cinematographer['name']
            doplist.append(itemdop)
        except KeyError as ke:
            print(f"电影ID{x}的摄影师数据无姓名字段")
            doplist.append("摄影师姓名缺失")

imdblistdop(items)
# 可打印完整结果校验
print("最终摄影师列表:", doplist)

改动说明

  • 给get方法新增了默认返回值空列表,从源头避免拿到None
  • 新增了多层非空、异常判断逻辑,所有空值/异常场景都做了兼容,不会因为单个电影数据异常中断整个遍历流程
  • 你可以根据自己的需求调整不同异常场景下的填充值,不需要存储空数据的话直接把append语句删掉,只保留continue跳过即可

内容的提问来源于stack exchange,提问作者teneb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:06:04