输入要翻译的内容时 , 地址并未发生变化,因此可断定是向接口发送的ajax请求
清空一下审查窗口,再点击一次翻译可以发现实际发送请求的url为https://fanyi.qq.com/api/translate
并且可以看到发送的是post请求,请求表单数据和响应数据都可以找到,复制form表单数据,然后换一个词翻译,同样复制form表单数据,比较两个表单数据有哪些不同,以方便去模仿构造数据
Form Data
source: auto
target: en
sourceText: 大象
qtv: fb7019db18d2efd2
qtk: tMDoh4iZnYF7a6MshJPtOvA7vXOMj0j+MUFcj6Ogl94MkIim6UUYl/KC4sv03GvVBnb2t6BbmOnew9ASvvKDh+sjJh7tOjLhy1W1M/S/xofJ469ZnMym2es4NJ2Ux8q3pZ0r/RCLPOPc15BSupGOcQ==
sessionUuid: translate_uuid1542022141842Form Data
source: auto
target: en
sourceText: 熊猫
qtv: fb7019db18d2efd2
qtk: tMDoh4iZnYF7a6MshJPtOvA7vXOMj0j+MUFcj6Ogl94MkIim6UUYl/KC4sv03GvVBnb2t6BbmOnew9ASvvKDh+sjJh7tOjLhy1W1M/S/xofJ469ZnMym2es4NJ2Ux8q3pZ0r/RCLPOPc15BSupGOcQ==
sessionUuid: translate_uuid1542022664896
可以看到 表单不同处只是输入的关键词和sessionUuid,看uuid后面的数字不知道是啥,有点像时间戳,去站长之家的工具箱搜了一下确实是毫秒制的时间戳(15位数字一般是时间戳,小写字母十六进制的一串一般是MD5、SHA1加密,大写字母加数字一般是Base64加密)
将Form表单数据粘到sublime正则匹配操作一波
用同样的方式处理一下请求头headers,并提取一下response里的翻译结果
最后代码如下,其中的form_dict要转下码 urlopen传参也要传data参数,这样才是post请求
#coding:utf-8
import urllib2
import urllib
import json
import timedef qq_fanyi(text):headers = {"Accept": "application/json, text/javascript, */*; q=0.01",# py2的urllib2不支持压缩# "Accept-Encoding": "gzip, deflate, br","Accept-Language": "zh-CN,zh;q=0.9","Connection": "keep-alive","Host": "fanyi.qq.com","Origin": "https://fanyi.qq.com","Referer": "https://fanyi.qq.com/","User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36","X-Requested-With": "XMLHttpRequest",# 请求体的长度"Content-Length": "288","Content-Type": "application/x-www-form-urlencoded; charset=UTF-8","Cookie": "fy_guid=1ebf7009-a752-4e96-9c00-6f1716ff5feb; pgv_info=ssid=s2052501920; ts_refer=www.baidu.com/link; pgv_pvid=6854096010; ts_uid=4010684990; gr_user_id=0d431726-9e54-48b8-9a03-ef467bab3c4f; grwng_uid=42c02436-79da-49fe-b367-4f577cfe293f; 9c118ce09a6fa3f4_gr_session_id=3eed6036-7a72-4c3d-8307-f49cc268ffd1; qtv=fb7019db18d2efd2; qtk=tMDoh4iZnYF7a6MshJPtOvA7vXOMj0j+MUFcj6Ogl94MkIim6UUYl/KC4sv03GvVBnb2t6BbmOnew9ASvvKDh+sjJh7tOjLhy1W1M/S/xofJ469ZnMym2es4NJ2Ux8q3pZ0r/RCLPOPc15BSupGOcQ==; ts_last=fanyi.qq.com/; openCount=2; 9c118ce09a6fa3f4_gr_session_id_3eed6036-7a72-4c3d-8307-f49cc268ffd1=true"}# 生成查询时的时间戳uuid = int(time.time() * 1000)form_dict ={"source":"auto","target":"en","sourceText":text,"qtv":"fb7019db18d2efd2","qtk":"tMDoh4iZnYF7a6MshJPtOvA7vXOMj0j+MUFcj6Ogl94MkIim6UUYl/KC4sv03GvVBnb2t6BbmOnew9ASvvKDh+sjJh7tOjLhy1W1M/S/xofJ469ZnMym2es4NJ2Ux8q3pZ0r/RCLPOPc15BSupGOcQ==","sessionUuid":"translate_uuid" + str(uuid)}form_data = urllib.urlencode(form_dict)headers['Content-Length'] = len(form_data)url = 'https://fanyi.qq.com/api/translate'request = urllib2.Request(url, form_data, headers=headers)response = urllib2.urlopen(request)# 从响应中提取翻译后的结果json_data = json.loads(response.read())result = json_data['translate']['records'][0]['targetText']print resultif __name__ == '__main__':while True:text = raw_input('请输入要翻译的内容[支持多种语言]:')qq_fanyi(text)