Python requests中chunk-size不生效,为何出现‘name 'chunk' is not defined’错误?
错误原因及修正方案
核心报错原因
你调用iter_content()时的参数写法完全错误:
正确的参数名是chunk_size(下划线分隔),赋值要用单等号=,但你写成了chunk-size==8。Python会把chunk-size解析成chunk - size的运算,而chunk和size这两个变量根本没定义,所以直接抛出name 'chunk' is not defined的错误。
其他需要修正的语法问题
除了核心错误,代码里还有几个Python语法规范问题,不修正也会导致报错:
- Python对大小写敏感,模块导入和关键字必须小写:
Import改为import,For改为for - 变量名要前后统一:定义的
Headers要改成headers,否则后面headers=headers会报另一个未定义错误 - 文件名建议和下载资源格式匹配:把
testfile.jpg改成testfile.webp,避免格式混淆
修正后的完整代码
import requests headers = {'range':'bytes=0-11'} r = requests.get('https://httpbin.org/image/webp', stream=True, headers=headers) with open('testfile.webp', 'wb') as file: for i in r.iter_content(chunk_size=8): write_len = file.write(i) print(write_len)
内容的提问来源于stack exchange,提问作者user19944660
相关产品推荐
相关产品推荐

