# 背景
最近想在工具集里面集成一个翻译功能(英文不好,解决命名问题)。搜了下翻译API,要么是sdk,要么是有次数限制。于是拿出来爬虫精神,瞄准了有道翻译,跟踪了有道前端代码,找到了接口参数拼装方式。
# 跟踪步骤
- 1 尝试下翻译,找到接口地址:http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
- 2 在xhr/fetch breakpoints下个断点包含(translate_o?smartresult=dict&smartresult=rule)
- 3 触发下请求,通过call stack找到fanyi.min.js(格式化)第8724行t.translate方法调用,分析下函数体就看到参数如何拼装的
# 具体模拟代码
// md5加密模块
var md5 = require('js-md5');
// 简化请求模块
var request = require('request');
const time = new Date().getTime();
const client = 'fanyideskweb';
const origin = 'what';
const D = "ebSeFb%=XZ%T[KZ)c(sy!";
const sign = md5(client + origin + time + D);
// 接口参数
const data = {
i: origin,
from: 'AUTO',
to: 'AUTO',
smartresult: 'dict',
client,
salt: time,
sign,
doctype: 'json',
version: '2.1',
keyfrom: 'fanyi.web',
action: 'FY_BY_REALTIME',
typoResult: false
}
// 必须的头信息
const headers = {
"Referer" : 'http://fanyi.youdao.com/',
"User-Agent" : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
};
// 启用cookie
const req = request.defaults({jar: true});
// 需要先请求一次翻译地址,拿到cookie, 表明是在一个session下的请求,
// 验证的cookie名是OUTFOX_SEARCH_USER_ID
req('http://fanyi.youdao.com/', function (err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
req({
method: 'POST',
url,
form: data,
headers,
gzip: true // 开启压缩
}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
})
← 浏览器中复制文本