网址

https://fanyi.baidu.com

python代码

# -*- coding: utf-8 -*-
# @Author: Null119 微信公众号/网站:治廷君
# @Desc: { 百度翻译 }
# @Date: { 2023-01-06 }

import requests
import re
import execjs

ctx = execjs.compile(open('./baidu.js',encoding='utf-8').read())
r = requests.Session()

def getTokenGtk():
    headers={
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Host':'fanyi.baidu.com',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'
        }
    resp=r.get('https://fanyi.baidu.com/',headers=headers).text
    resp = r.get('https://fanyi.baidu.com/', headers=headers).text
    gtk=re.search(r'window\.gtk = "(.*?)"',resp).group(1)
    token=re.search(r"token: '([a-z0-9]{32})'",resp).group(1)
    return token,gtk

def getTS():
    resp=r.get('https://dlswbr.baidu.com/heicha/mm/2060/acs-2060.js').text
    runtext=re.search(r'p\.run\(.*?\)',resp).group()
    ts=re.search(r'[\d+]{13}',runtext).group()
    return ts

def getData(words,token,gtk,ts):
    key='aiyyeswmsceomsaa'
    while True:
        acstoken=ts+str(ctx.eval('AcsToken("https://fanyi.baidu.com/#en/zh/' +words +'","'+key+'")'))
        sign=str(ctx.eval('sign("' + words + '","'+gtk+'")'))
        pdat={
            "from":"en",
            "to":"zh",
            "query":words,
            "transtype":"realtime",
            "simple_means_flag":"3",
            "sign":sign,
            "token":token,
            "domain":"common"
        }
        r.headers['Acs-Token'] = acstoken
        resp= r.post('https://fanyi.baidu.com/v2transapi?from=en&to=zh',data=pdat)
        if 'errmsg' in resp.json():
            if key=='aiyyeswmsceomsaa':key='meaaauoegemaaaqs'
            else:key == 'aiyyeswmsceomsaa'
        else:
            print('Acs-Token:', acstoken)
            print('Token:',token)
            print('sign:', sign)
            print('翻译内容:',words,', 翻译结果:',resp.json()['trans_result']['data'][0]['dst'])
            break

if __name__ == '__main__':
    token,gtk=getTokenGtk()
    ts=getTS()
    words='happy'
    getData(words,token,gtk,ts)

baidu.js(Acs-token、Sign生成)

请输入暗号查看内容(暗号有效期3天,全站通用)
请关注本站微信公众号,回复“暗号”获取。在微信里搜索公众号“治廷君”或者“ztkjgzs”或者微信扫描右侧二维码关注本站微信公众号。
如果觉得我的文章对你有用,请随意赞赏