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

Python 3.9环境下urllib.request.urlopen报TypeError: can't concat str to bytes错误的解决方案咨询

解决TypeError: can't concat str to bytes的问题

嘿,我一眼就瞅到问题出在哪了——你用urllib.request.urlopen的方式不对!

错误根源

urllib.request.urlopen的第二个参数是要POST的字节类型数据(data),而不是请求头(headers)。你直接把headers字典传给了第二个参数,Python会把它当成data来处理,内部在拼接数据时就会出现「字符串和字节无法拼接」的错误,也就是你看到的TypeError: can't concat str to bytes。

可行的解决方法

1. 用Request对象封装请求头和链接

这是urllib库添加请求头的标准姿势,先构造Request对象,再传给urlopen:

import urllib.request
import urllib.error

try:
    # 先构造Request对象,明确指定headers参数
    req = urllib.request.Request(link, headers=headers)
    with urllib.request.urlopen(req) as f:
        print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
    print(e.reason)

2. 检查headers的格式

确保你的headers字典里的所有键和值都是字符串类型,不要混入字节数据,否则后续请求可能还会出现其他编码相关的问题。

3. 如果需要发送POST数据(可选)

要是你本来就打算发送POST请求,那data参数需要转换成字节类型,比如:

data = urllib.parse.urlencode({"key": "value"}).encode('utf-8')
req = urllib.request.Request(link, data=data, headers=headers)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:17:31