# post请求爬虫

from urllib import request,parse
import re
import time

headers = {
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
}

url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"


def translate(key):

    form_data = {
        "i": key,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": "15864428750383",
        "sign": "b07e6a9a1baed3b580e9baad441dbf91",
        "ts": "1586442875038",
        "bv": "9fab1cc63c05964eaf4254cc4acb7cad",
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_REALTlME"
    }

    data = parse.urlencode(form_data).encode(encoding="utf-8")
    req = request.Request(url,data=data,headers=headers)
    resp = request.urlopen(req).read().decode()

    pat = r'"tgt":"(.*?)"}]]'   #正则表达式,(.*?)表达这个字符为任意字符

    translate_result = re.findall(pat,resp)     #re.findall()表示提取pat中的正则表达式字符。
    print(translate_result[0])
    time.sleep(1)
    print("------------------------")
    time.sleep(1)
if __name__ == '__main__':
    while True:
        enter = input("输入需要翻译的文字:")
        translate(enter)

扫描二维码,在手机上阅读!
最后修改:2020 年 04 月 09 日 11 : 49 PM
如果觉得我的文章对你有用,请随意赞赏