Python爬虫案例1之有道翻译

有道翻译爬虫

import requests      # 需安装
import  time
import random
import hashlib      # 需安装,md5加密
import jsonpath     # 需安装,解析json数据

def youdao(sentence):

    lts = str(int(time.time()*1000))
    salt = lts + str(random.randint(0, 9))
    sign = "fanyideskweb" + sentence + salt + "]BjuETDhU)zqSxf-=B#7m"
    sign = hashlib.md5(sign.encode()).hexdigest()

    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    
    head = {"User-Agent": "",	# 需使用自己的浏览器代理
            "Referer": "http://fanyi.youdao.com/",
            "Cookie": "",	# 需使用自己的浏览器产生的Cookie
            }

    formdata = {
        "i": sentence,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb", 
        "salt": salt,      # 时间戳加随机数
        "sign": sign,	
        "lts": lts,	# 时间戳
        "bv": "",	# 由用户代理md5加密得到,此项不变,需自己从浏览器中复制
        "doctype": "json
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_REALTlME",
    }
    res = requests.post(url, data=formdata, headers=head)
    json_data = res.json()
    # print(json_data)
    result = jsonpath.jsonpath(json_data, "$..tgt")[0]
    print(result)

if __name__ == '__main__':
    while True:
        str1 = input("有道翻译为您服务,请输入:\n")
        # 输入q退出
        if str1 == 'q':
            break
        youdao(str1)
posted @ 2020-11-13 08:15  流水自净  阅读(133)  评论(0编辑  收藏  举报