Pythonゼロベースpostリクエストによる有道翻訳ウィジェット(urllib,request,post,parse,json)
8923 ワード
# !/usr/bin/python
# Filename: post .py
# Data : 2020/07/16
# Author : --king--
# ctrl+alt+L
import urllib.request
import urllib.parse
import json
# : post
#
key = input(' :')
# POST
data = {
'i': key,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '15949097071450',
'sign': '51d443b018a380fed2e86bd67dfbeace',
'ts': '1594909707145',
'bv': '0ea2f265e69dc7094ed5f0b64ef39e0b',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION'
}
# print(data)
# urllib parse.urlencode() , key:value "key=value" , ASCII
data = urllib.parse.urlencode(data)
# print(data)
# POST , data
data = bytes(data,'utf-8')
# url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
# ,_o ,url
# http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
# header
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
# , post
req = urllib.request.Request(url,data,headers=headers)
#
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
# , , json
# post data , json
# print(html,type(html))
# json.loads
result_temp = json.loads(html)
# print(result,type(result))
# , k-v
result = result_temp['translateResult'][0][0]
# ,
if key == result['src']:
print(' :',key)
print(' :',result['tgt'])
else:
print(' , ')