bv: fdac15c78f51b91dabd0a15d9a1b10f5
doctype: json
version: 2.1
keyfrom: fanyi.web
action: FY_BY_REALTlME
对于这些数据,写到代码中还需要一定的操作。
因为是放在字典中,所以都要加上字符串。可以使用正则替换快速完成:ctrl + r ,(.*): (.*) “$1”:“$2”
再就是我们实际翻译不只翻译你好这一个词,所以把“你好”换成变量名key。
修改好后的形式见代码中。
=================================================================================
import urllib.request
import urllib.parse
import json
要进行输入内容
key = input(“请输入内容:”)
data = {
“i”: key,
“from”: “AUTO”,
“to”: “AUTO”,
“smartresult”: “dict”,
“client”: “fanyideskweb”,
“salt”: “16374132986488”,
“sign”: “dfd139af546a8cd63de0676f446ca2ee”,
“lts”: “1637413298648”,
“bv”: “03a6a27012b22bc3c7ecc76381772182”,
“doctype”: “json”,
“version”: “2.1”,
“keyfrom”: “fanyi.web”,
“action”: “FY_BY_REALTlME”,
}
字节流,如果输入中文,需要处理的
data = urllib.parse.urlencode(data) # 转为十六进制形式
data = bytes(data, encoding=‘utf8’) # 转为字节流
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36’
}
目标url发请求
{“errorCode”:50} ,把_o
url = ‘https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule’
构建请求对象
req = urllib.request.Request(url, data=data, headers=headers)
发请求,获取响应对象
res = urllib.request.urlopen(req)
print(res.getcode()) # 得到响应码,200表示请求成功
html = res.read().decode(‘utf-8’)
print(type(html)) # <class ‘str’>,得到的是json数据
json数据转字典
dic = json.loads(html)
result = dic[“translateResult”] # [[{‘src’: ‘你好’, ‘tgt’: ‘hello’}]]
print(result[0][0][‘tgt’])
结果如图所示:
===================================================================================
import requests
import json
请输入要翻译的内容
key = input(“请输入:”)
携带的数据
data = {
“i”: key,
“from”: “AUTO”,
“to”: “AUTO”,
“smartresult”: “dict”,
“client”: “fanyideskweb”,
“salt”: “16374132986488”,
“sign”: “dfd139af546a8cd63de0676f446ca2ee”,
“lts”: “1637413298648”,
“bv”: “03a6a27012b22bc3c7ecc76381772182”,
“doctype”: “json”,
“version”: " 2.1",
“keyfrom”: “fanyi.web”,
“action”: “FY_BY_REALTlME”,
}
url = ‘https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule’
headers ={
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36’