爬取Shopee评论时追加JSON到列表出现'NoneType object is not iterable'错误
报错原因
报错触发位置为get_ratings函数中的遍历代码for i, rating in enumerate(data["data"]["ratings"], 1):。当接口返回data["data"]["ratings"]为null(对应Python中的None)时,enumerate方法尝试遍历None对象,直接触发'NoneType' object is not iterable类型错误,该问题和你之前排查的单个字段空值、键缺失场景无关。
修复方案
对ratings字段做非空兼容处理即可,同时可补充基础的请求异常捕获逻辑避免网络波动导致程序崩溃,修改后的get_ratings函数代码如下:
def get_ratings(shop_id, item_id): ratings_url = "https://shopee.sg/api/v2/item/get_ratings?filter=0&flag=1&itemid={item_id}&limit=20&offset={offset}&shopid={shop_id}&type=0" offset = 0 d = {"product_id": [], "username": [], "rating": [], "comment": []} while True: # 可选:新增请求异常捕获,避免网络问题导致程序退出 try: resp = requests.get( ratings_url.format(shop_id=shop_id, item_id=item_id, offset=offset) ) resp.raise_for_status() data = resp.json() except Exception as e: print(f"请求商品{shop_id}_{item_id}评论失败:{str(e)}") break # 核心修复:对ratings做非空兼容,为None时默认转换为空列表 ratings = data.get("data", {}).get("ratings") or [] i = 1 for i, rating in enumerate(ratings, 1): d["product_id"].append(rating["itemid"]) d["username"].append(rating["author_username"]) d["rating"].append(rating["rating_star"]) d["comment"].append(rating["comment"]) if i % 20: break offset += 20 return d
另外注意你现有代码中定义headers时用到的Shopee_url变量未提前声明,需要补充Shopee_url = "https://shopee.sg/"定义,否则会触发变量未定义报错。
内容的提问来源于stack exchange,提问作者Donovan Tan
相关产品推荐
相关产品推荐

