python3爬虫问题,API调用出现282004等错误

   下面是一些错误: 

"error_code": 282004,

 "error_msg": "invalid parameter(s)",
a bytes-like object is required, not 'str'
POST data should be bytes or an iterable of bytes
Content-Length should be specified for iterable data of type <class 'dict'> {'text': '昆明会下雨吗?'}

等一系列都是因为数据格式的原因

1、Content-Length should be specified for iterable data of type <class 'dict'>

这里是因为request 参数不能dict或json

post_data = {"text":"昆明会下雨吗?"}
data=json.dumps(post_data).encode('GBK')
request = urllib.request.Request(url, data)
#JSON:在发起请求时,需要发送一个已经过编译的JSON数据:

data=json.dumps(post_data).encode('GBK')

2、a bytes-like object is required, not 'str'
POST data should be bytes or an iterable of bytes,这里是要提醒

注意区分bytes和str,需要格式转换。#bytes ⇒ str:str(b, encoding='****')

response = urllib.request.urlopen(request)
content = response.read()  # content是一个utf-8格式的<class 'bytes'>
#bytes ⇒ str:str(b, encoding='****')
content_str = str(content, encoding="gbk")

3、参数错误,对照API接口查看body

"error_code": 282004, "error_msg": "invalid parameter(s)",

# 用下一行是对的post_data ="{\"text\":\"昆明会下雨吗?\"}"
post_data = {"text":"昆明会下雨吗?"}
data=json.dumps(post_data).encode('GBK')
request = urllib.request.Request(url, data)

猜你喜欢

转载自blog.csdn.net/shuihupo/article/details/79869856
今日推荐