欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type s

程序员文章站 2022-07-15 15:36:31
...

我在是 学习的时候,代码中是python2.x 的版本用的是urllib2 库
我是改为urllib.requst

运行是提示

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str

解决办法。在 # 编码
data = urllib.parse.urlencode(submit_data).encode(“utf-8”)

# 编码(这个本来没有指定格式编码)
# data = urllib.parse.urlencode(submit_data)
# 加上encode("utf-8")
data = urllib.parse.urlencode(submit_data).encode("utf-8")


# 构造请求头,创建请求对象
headers = {
    "Accept" : "application/json, text/plain, */*",
    "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.7 Safari/537.36",
    "Accept-Language" : "zh-CN,zh;q=0.8"
}

req = urllib.request.Request(url,data,headers)

# 发送请求
response = urllib.request.urlopen(req)