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

含with...as语句的Python循环报错求助:IndentationError

解决你的IndentationError和循环问题

首先,你的核心问题是Python的缩进规则——Python依赖缩进(而非大括号)划分代码块,with...as语句冒号后面必须跟着一个缩进的代码块,这就是你触发IndentationError: expected an indented block的原因。另外还有个潜在坑:如果data没有预先初始化,直接通过data[i]赋值会抛出索引错误。

贴合你习惯的修正版代码

先给你最匹配原有写法的解决方案,保留for i in range(10)的结构:

import urllib.request, json

# 预先初始化data列表,确保有10个位置可赋值
data = [None] * 10
# 假设你已经定义好包含10个有效URL的baselink列表
baselink = ["https://example.com/api/1", "https://example.com/api/2", ..., "https://example.com/api/10"]

for i in range(10):
    with urllib.request.urlopen(baselink[i]) as url:
        # 这里必须缩进(建议用4个空格,保持风格统一),表示属于with代码块
        response_content = url.read().decode()
        data[i] = json.loads(response_content)

错误原因拆解

你之前的代码里,with语句后的data[i] = ...没有缩进,Python会判定with没有对应的代码块,直接抛出缩进错误。只要把with块内的代码统一缩进,这个问题就能解决。

更简洁的Pythonic写法(推荐)

如果不需要手动控制索引,直接遍历baselink会更灵活,还不用提前指定列表长度:

import urllib.request, json

baselink = ["https://example.com/api/1", "https://example.com/api/2", ...]
data = []

for link in baselink:
    with urllib.request.urlopen(link) as url:
        response_content = url.read().decode()
        data.append(json.loads(response_content))

# 此时data[0]对应第一个URL结果,data[1]对应第二个,以此类推

额外的健壮性优化

实际场景中,网络请求或JSON解析可能失败,建议添加异常处理,避免单个请求出错导致整个循环终止:

import urllib.request, json
from urllib.error import URLError

baselink = ["https://example.com/api/1", "https://example.com/api/2", ...]
data = []

for idx, link in enumerate(baselink):
    try:
        with urllib.request.urlopen(link) as url:
            response_content = url.read().decode()
            data.append(json.loads(response_content))
    except URLError as e:
        print(f"请求第{idx+1}个URL失败: {str(e)}")
        data.append(None)  # 用None标记失败的请求
    except json.JSONDecodeError as e:
        print(f"解析第{idx+1}个URL的JSON失败: {str(e)}")
        data.append(None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:23:30