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

Python OLX爬虫运行报NoneType不可迭代TypeError错误 求排查修复

错误原因定位

错误出现在anuncios.extend(anuncios_da_pagina)这行,根因是get_anuncios()函数在以下三种场景会直接返回None:

  • 调用get_site_html()请求页面返回空
  • 调用get_bsobj_from()解析HTML失败
  • 查找广告列表元素时抛出AttributeError异常
    而列表的extend()方法要求传入参数必须是可迭代对象,None不属于可迭代对象,因此触发TypeError。

另外代码还存在一个隐性问题:get_anuncio()也可能返回None,当前代码直接将返回值追加到列表中,最终导出CSV时会出现无效空值。

修复方案

1. 新增get_anuncios()返回值非空校验

修改run()函数中调用get_anuncios()后的逻辑,仅当返回值非空时才执行合并操作:

anuncios_da_pagina = get_anuncios(url_formatada)
if anuncios_da_pagina is not None:
    anuncios.extend(anuncios_da_pagina)
else:
    print(f"第{pagina_atual}页数据获取失败,已跳过")

2. 过滤get_anuncio()返回的空值

修改get_anuncios()函数中遍历广告链接的逻辑,仅将有效非空的广告数据追加到列表:

for link_anuncio in links_for_anuncios:
    anuncio = get_anuncio(link_anuncio['href'])
    if anuncio is not None:
        anuncios.append(anuncio)
        print(anuncio)
        print(" ")

可选优化

可以给get_site_html()增加重试次数、超时时间设置,降低网络波动、反爬拦截导致的获取失败概率。

内容的提问来源于stack exchange,提问作者asim-biosint

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:36:01