QQ翻译案例
本案例通过分析QQ翻译的行为,找到了翻译数据得请求接口!
在使用的时候,注意请求头要尽量真实,尤其要注意User-Agent和Content-Length值的填写正确
请求的数据格式要与接口中定义的相同
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | def test03():
url = "https://fanyi.qq.com/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
}
request = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode("UTF-8")
regex = '\s{8}var\sqtv\s=\s"(.*?)";\n\s{8}var\sqtk\s=\s"(.*)";'
result = re.search(regex,content)
if result :
return (result.group(1),result.group(2))
else:
print("匹配失败")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 | def test04():
qtv,qtk = test03()
data = {
"source": "auto",
"target": "zh",
"sourceText": input("请输入你要翻译的文本:"),
"sessionUuid": "translate_uuid"+str(int(time.time()*1000)),
"qtv":qtv,
"qtk":qtk
}
data = urllib.parse.urlencode(data).encode()
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Origin": "https://fanyi.qq.com",
"Referer": "https://fanyi.qq.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"Content-length":len(data)
}
url = "https://fanyi.qq.com/api/translate"
req = urllib.request.Request(url,data,headers)
resp = urllib.request.urlopen(req)
content = resp.read().decode()
content = json.loads(content)
targetText = content["translate"]["records"][0]["targetText"]
print("翻译的结果为:",targetText)
def translateDemo():
while True:
test04()
if __name__ == '__main__':
translateDemo()
|