小甲鱼python 课程中有道翻译爬虫教学中添加head时报错
UnicodeEncodeError: ‘latin-1’ codec can’t encode character ‘\u2026’ in position 30: ordinal not in range(256)
代码如下
import urllib.request
import urllib.parse
import json
url=“http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule”
content=input(“请输入需要翻译的内容:”)
head={}
head[“User-Agent”]=“Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/73.0”
data={}
data[“i”]=content
data[“client”]=“fanyideskweb”
data[“salt”]=“15833279825455”
data[“sign”]=“2d617a68459249bb1a01e7a4965fba39”
data[“ts”]=“1583327982545”
data[“bv”]=“e2a78ed30c66e16a857c5b6486a1d326”
data[“tgt”]=“I+love+fish+c+studio”
data[“from”]=“zh-CHS”
data[“to”]=“en”
data[“doctype”]=“json”
data[“version”]=“3.0”
data[“cache”]=“true”
data=urllib.parse.urlencode(data).encode(“utf-8”)
req=urllib.request.Request(url,data)
“”"
req.add_header(“User-Agent”,“Mozilla/5.0 (Windows NT 10.0;) Gecko/20100101 Firefox/73.0”)
“”"
response=urllib.request.urlopen(req)
html=response.read().decode(“utf-8”)
target=json.loads(html)
t=target
print(t[“translateResult”][0][0][“tgt”])
错误原因是
head[“User-Agent”]=“Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/73.0”
去掉用户代理head中**…**即可