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

无法按顺序执行嵌套循环?附Python爬虫代码求助

问题排查与修复

核心问题

你的嵌套循环失效的原因是**sayac变量初始化位置错误**:如果sayac是在整个外层for循环之外定义的,第一次外层循环(处理kıloldum[0])就会把sayac递增到len(liste),第二次外层循环(处理kıloldum[1])时,while len(liste) > sayac的条件直接不成立,导致后续的链接爬取逻辑完全跳过。

修复后的代码

把sayac的初始化移到外层for循环内部,确保每次处理kıloldum的一个元素时,都从头遍历liste的所有链接:

for lop in range(len(kıloldum)):
    sayac = 0  # 每次外层循环都重置计数器
    while len(liste) > sayac:
        nw = req.get(liste[sayac], headers=headers)
        nh = nw.text
        nb = btu(nh, "lxml")
        tablo = nb.find_all("div", {"class": "block-body js-replyNewMessageContainer"})
        for findwp in tablo:
            mesaj = findwp.find_all(string=kıloldum[lop])
            if mesaj:  # 直接判断非空,替代空列表判断
                ii.append(mesaj)
        sayac += 1

可选优化建议

  • 把while循环换成更直观的for循环遍历liste,避免手动维护计数器,代码可读性更高:
for keyword in kıloldum:  # 直接遍历元素而非索引,逻辑更清晰
    for url in liste:
        nw = req.get(url, headers=headers)
        nh = nw.text
        nb = btu(nh, "lxml")
        tablo = nb.find_all("div", {"class": "block-body js-replyNewMessageContainer"})
        for findwp in tablo:
            mesaj = findwp.find_all(string=keyword)
            if mesaj:
                ii.append(mesaj)
  • 建议添加请求异常处理(比如try-except块),避免单个请求失败导致整个爬虫中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:02:02