有道词典爬虫-2020年3月亲测还有用

import urllib.request
import urllib.parse
import json
f=input('输入需要翻译的中文:')
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'#这里原地址有一个**_o**需要删除
data={"i":f,"from":"AUTO","to":"AUTO","smartresult":"dict","client":"fanyideskweb","salt":"15849676799497",\
      "sign":"22d2f8519efb85bae17e5d3cbf1723b5","ts":"1584967679949","bv":"0930ba55ca8c5e4b94b06e3db8ae8b55",\
      "doctype":"json","version":"2.1","keyfrom":"fanyi.web","action":"FY_BY_REALTlME"}
data=urllib.parse.urlencode(data).encode('utf-8')#自定义response中的POST部分并转译为utf-8(urlencode为ASCII格式)
response=urllib.request.urlopen(url,data)
html=response.read().decode('utf-8')
word1=json.loads(html)
word2=word1['translateResult'][0][0]['tgt']

print(word2)

运行结果

D:\recent\code\venv\Scripts\python.exe D:/recent/code/venv/FC.py
输入需要翻译的中文:人生苦短,我用python
Life is too short, I use python

进程已结束,退出代码0

睡五秒一个循环

import json
import time
while True:
    f = input('输入需要翻译的句子(输入"q"退出程序):')
    if f=='q':
        break
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    data = {"i": f, "from": "AUTO", "to": "AUTO", "smartresult": "dict", "client": "fanyideskweb",
            "salt": "15849676799497", \
            "sign": "22d2f8519efb85bae17e5d3cbf1723b5", "ts": "1584967679949", "bv": "0930ba55ca8c5e4b94b06e3db8ae8b55", \
            "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "action": "FY_BY_REALTlME"}
    data = urllib.parse.urlencode(data).encode('utf-8')  # 自定义response中的POST部分并转译为utf-8(urlencode为ASCII格式)
    h = {}
    h['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363'  # 隐藏
    req = urllib.request.Request(url, data, h)
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf-8')
    word1 = json.loads(html)
    word2 = word1['translateResult'][0][0]['tgt']

    print(word2)
    time.sleep(5)

运行

D:\recent\code\venv\Scripts\python.exe D:/recent/code/venv/FC.py
输入需要翻译的句子(输入"q"退出程序):你好
hello
输入需要翻译的句子(输入"q"退出程序):你好吗?
How are you?
输入需要翻译的句子(输入"q"退出程序):q

进程已结束,退出代码0

发布了19 篇原创文章 · 获赞 7 · 访问量 876

猜你喜欢

转载自blog.csdn.net/Pyouthon/article/details/105059627