Python调用有道web端翻译,翻译中英文
来源:互联网 发布:java的基础知识 编辑:程序博客网 时间:2024/06/08 06:37
这段代码写了都好久了,最近在整理,写个文章记录一下,或许能帮助一二。
话不多说,直接上代码吧。
# coding *utf-8*import urllib.requestimport urllib.parseimport jsonimport timedef postHtml(url,data,header): """提交需进行翻译的数据表单,url是有道翻译的地址,data是提交表单数据, header是浏览器的一些头信息;函数返回值'非真即假'""" try: head = header data = urllib.parse.urlencode(data).encode('utf-8')#表单数据处理 response = urllib.request.urlopen(url,data)#发起请求 toBeJson = response.read().decode('utf-8')#数据解码为'utf-8'(一般不是utf-8,就是gbk) afterJson = json.loads(toBeJson)#数据解析成json格式 return afterJson except Exception as e: print('get Http Request Error: %s' % e) return Falseprint('Welcome to Youdao Dictionary from chen!')URL = 'http://fanyi.youdao.com/translatesmartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'HEAD = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}DATA = {'type':'AUTO', #'i':target, 'doctype':'json', 'xmlVersion':'1.8', 'keyfrom':'fanyi.web', 'ue':'UTF-8', 'action':'FY_BY_CLICKBUTTON', 'typoResult':'true'}while True: target = input('input:')#输入需要翻译的中文或英文 if target == 'shutdown':#如果输入字符'shutdown'那么退出翻译函数 print('Thank you for using the script!') break else: DATA['i'] = target html = postHtml(URL, DATA,HEAD)#数据返回为真时,输出翻译结果 if html: try: #当有道能翻译出该单词,那么那么返回翻译结果 print(html['smartResult']['entries'][1]) except KeyError: #当有道不能翻译出该单词(eg:ajdfkla),那么会返回输入单词本身 print(html['translateResult'][0][0]['tgt'])time.sleep(2)
可能你对浏览器头文件,提交的表单数据不是很了解。
简单介绍下:
一般需要数据交互的都是post请求,在浏览器上可以查看先找到post请求的链接
谷歌浏览器下,按F12,在Network下,根据method方法可查看是post请求还是get请求。
点击此链接,可以查看浏览器头数据——Request Headers
下拉【header】数据栏,有Form Data数据
点击【Response】栏,可查看请求数据后,返回的结果
好了,刚写上博客,写的粗略还请见谅。
0 0
- Python调用有道web端翻译,翻译中英文
- 【3】python有道调用API进行翻译
- [python爬虫]--调用有道词典进行翻译
- python有道翻译
- Python实现有道翻译
- Python:有道翻译
- Java 调用 有道翻译API
- java调用有道翻译接口
- 有道词典Python模拟翻译
- python爬虫04--有道翻译
- 【python爬虫小实战】python3.x用requests和bs4实现有道翻译(中英文)
- Asp.NET调用有道翻译API
- Asp.NET调用有道翻译API
- Python 实现有道翻译命令行版
- 用python写一个命令行有道翻译
- Python抓取有道翻译,得到在线翻译结果
- Python 爬虫 :简单的爬有道翻译
- Python学习的有道及Google翻译
- Java-类库-Guava-cache
- 使用开源框架smart image view实现网络资源照片设置到ImageView控件
- jadclipse插件安装
- Git 内部原理 - 维护及数据恢复
- 面向对象之第一个程序
- Python调用有道web端翻译,翻译中英文
- 湘潭oj_1250 Super Fast Fourier Transform
- 初次邂逅Hibernate之环境配置
- AFNetWorking(3.0)源码分析(一)——基本框架
- Java集合 asList的缺陷
- 数据库优化
- Java-类库-Guava-EventBus
- 微信支付
- 线段树练习4