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

xiaoxiao2021-02-28  49

   下面是一些错误: 

"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)
转载请注明原文地址: https://www.6miu.com/read-2631712.html

最新回复(0)