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

python3.8爬虫有道翻译报错' POST data should be bytes or an iterable of bytes'

程序员文章站 2022-07-15 15:39:43
...

原因:
请求数据时,没有编码成UTF-8
对策:
data = urllib.parse.urlencode(url).encode(encoding=‘utf-8’)

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus) 
Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string.

附上源代码

import urllib.request
import urllib.parse
import json
content=input('请输入需要翻译的内容:')
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data={}
data['i']=content
data['from']='AUTO'
data['to']='AUTO'
data['smartresult']='dict'
data['client']='fanyideskweb'
data['salt']='15887563211205'
data['sign']='4b838a13d4fe1cef23757c4fac68800e'
data['ts']='1588756321120'
data['bv']='8c141f1c08d20ba375b67e3d88fc7c4f'
data['doctype']='json'
data['version']='2.1'
data['keyfrom']='fanyi.web'
data['action']='FY_BY_REALTlME'
data=urllib.parse.urlencode(data).encode('utf-8')
#请求数据需要编码成utf-8,默认的是ASCII
response=urllib.request.urlopen(url,data)
html=response.read().decode('utf-8')
#python3.8默认编码形式是utf-8,因此可以写成html=response.read()
target=json.loads(html)
print('翻译结果是:%s'%(target['translateResult'][0][0]['tgt']))

相关标签: python

上一篇: hash算法

下一篇: Hash算法