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

Python爬取Booking数据时出现'NoneType' object is not iterable错误如何解决

问题背景

你在使用Python爬取Booking平台酒店数据时,运行到for h in data["hotels"]:代码行触发报错:'NoneType' object is not iterable

报错原因
  • 代码仅判断了返回的data对象非空,但没有校验data中hotels字段的有效性:当网页解析器未提取到任何酒店数据时,data["hotels"]会返回None而非空列表,遍历None对象就会触发该报错。
  • 小概率触发场景:请求被Booking反爬策略拦截,返回的页面不是正常酒店列表页;或是booking.yml配置的提取规则和当前Booking平台的网页结构不匹配,无法正确解析出酒店数组。
修复方案
  1. 新增hotels字段有效性校验,修改主逻辑的循环代码:
    原代码片段:
if data:
    for h in data["hotels"]:
        writer.writerow(h)

修改后:

# 同时校验data存在,且hotels字段非空、可遍历
if data and data.get("hotels"):
    for h in data["hotels"]:
        writer.writerow(h)

使用data.get("hotels")还能规避data中不存在hotels键时抛出KeyError的问题。

  1. 补充请求有效性校验,避免异常响应进入解析逻辑,修改scrape函数的请求部分:
r = requests.get(url, headers=headers)
# 新增状态码校验,请求失败直接返回None
if r.status_code != 200:
    print(f"请求{url}失败,状态码:{r.status_code}")
    return None
return e.extract(r.text,base_url=url)
  1. 其他稳定性优化:
  • 若频繁触发反爬,可更换User-Agent、添加代理IP、增加相邻请求的间隔时间
  • 定期检查booking.yml的提取规则,匹配Booking平台最新的网页结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:45:00