Simple implementation of Baidu translation by Python crawler

Tuffer tuffer 2020-11-14 22:17:47
simple implementation baidu translation python


Environmental Science

python Version number System Tourist device
python 3.7.2 win7 google chrome

About this article

This article will achieve simple Baidu translation through the way of crawler . The code in this article is for learning only , It is not allowed to be used for business purposes . Please go to api.fanyi.baidu.com Buy paid api. If there is an invasion , Delete immediately !

Realize the idea

Find hidden free in website files api. Pass in api The required parameters and request them . In the returned json The corresponding translation results are found in the results .

The anti climbing mechanism of Baidu translation
  • from js Algorithm generated sign
  • cookie testing
  • token Code

Find hidden free in website files api

Get into Baidu translation , Just type in any text that needs to be translated . When the translation results come out , Press down F12, Select to NETWORK, Finally, click in XHR file . This is the time , The website files have been loaded , So we need to F5 refresh .

python Reptiles Simple implementation of Baidu translation

After refreshing , We can find one with v2transapi? Opening file , you 're right , It's what we're looking for api Interface . Let's verify , Click in the file -preview, We can do that json In the format of the data found in the translation results , Verify success .
in addition , We also need to get our cookie and token, We need to use them in the later anti climbing mechanism , The location is as follows .
cookie Location :

python Reptiles Simple implementation of Baidu translation
token Location :

python Reptiles Simple implementation of Baidu translation

api Information

Interface : https://fanyi.baidu.com/v2tra...

Request mode :post

Request parameters

Parameters Introduce
from source language
to target language
query Translation text
sign from js The signature generated by the algorithm ( Anti creeping )
token Ask for a code

Start writing code

Import request and execjs library

import requests
import execjs
  • requests HTTP library , For reptiles
  • execjs Used to invoke js Code

Reflect the crawler

Because Baidu translation has cookie Identify the anti creep mechanism , So we set up what we just got cookie To cover the web spider identity .

headers = {'cookie':' Please enter your cookie'}

in addition , We have to set up token( Code ).

token = ' Please put your here token'

At the end of the day sign Anti climbing mechanism ,sign By js The algorithm generates a signature for the translation . I searched the Internet for , Found the corresponding js Algorithm , Share with you .

var i = "320305.131321201"
function n(r, o) {
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a), a = "+" === o.charAt(t + 1) ? r >>> a : r << a, r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
function e(r) {
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr(-10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++) "" !== e[C] && f.push.apply(f, a(e[C].split(""))), C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice(-10).join(""))
}
var u = void 0, l = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
u = null !== i ? i : (i = window[l] || "") || "";
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A : (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224, S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128)
}
for (var p = m, F = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++) p += S[b], p = n(p, F);
return p = n(p, D), p ^= s, 0 > p && (p = (2147483647 & p) + 2147483648), p %= 1e6, p.toString() + "." + (p ^ m)
}

wait , We're not using python Do you want to crawl ? Then we're not going to js Code , How to call ?
not so bad python With a powerful third-party library , Of course, it is necessary to call js Code library . call js A lot of code base , But I still recommend that you use execjs, Simple and complete .

Calling js Before the algorithm code , We also need to have the user type in a translation .

q = input(' translate :')

Then we can use execjs Of compile and call Method to get sign 了 .

js = '''var i = "320305.131321201"
function n(r, o) {
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a), a = "+" === o.charAt(t + 1) ? r >>> a : r << a, r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
function e(r) {
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr(-10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++) "" !== e[C] && f.push.apply(f, a(e[C].split(""))), C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice(-10).join(""))
}
var u = void 0, l = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
u = null !== i ? i : (i = window[l] || "") || "";
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A : (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224, S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128)
}
for (var p = m, F = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++) p += S[b], p = n(p, F);
return p = n(p, D), p ^= s, 0 > p && (p = (2147483647 & p) + 2147483648), p %= 1e6, p.toString() + "." + (p ^ m)
}
'''
sign = execjs.compile(js).call("e",q)

( The above code gets sign)

After a series of anti crawler preparations , We can set it up “ source language ” and “ target language ” The last two parameters .

From = 'en'
To = 'zh'

( The above code represents the English Chinese translation , If you want to translate other languages , Please enter the abbreviation for the language , The list of abbreviations will be placed at the end of this article )
next , We can build parameters json 了 .

data = {'from':From,
'to':To,
'query':q,
'sign':sign,
'token':'14b5f31e3c65d89a0b1c3f756e53942e'}

Last , We can request the data and print it .

text = requests.post(url,headers=headers,data=data).json()
print(text)

We found out that the printed result was a json Dictionaries , The translation result is in it , We just need to translate the result , So we can index the location of the translation results and print it .

text = requests.post(url,headers=headers,data=data).json()['trans_result']['data'][0]['dst']
print(text)

Running results :

python Reptiles Simple implementation of Baidu translation

Complete code :

import requests
import execjs
url = 'https://fanyi.baidu.com/v2transapi'
headers = {'cookie':' Yours cookie'}
js = '''var i = "320305.131321201"
function n(r, o) {
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a), a = "+" === o.charAt(t + 1) ? r >>> a : r << a, r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
function e(r) {
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr(-10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++) "" !== e[C] && f.push.apply(f, a(e[C].split(""))), C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice(-10).join(""))
}
var u = void 0, l = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
u = null !== i ? i : (i = window[l] || "") || "";
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A : (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224, S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128)
}
for (var p = m, F = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++) p += S[b], p = n(p, F);
return p = n(p, D), p ^= s, 0 > p && (p = (2147483647 & p) + 2147483648), p %= 1e6, p.toString() + "." + (p ^ m)
}
'''
From = ' source language '
To = ' target language '
token = ' Yours token'
q = input(' translate :')
sign = execjs.compile(js).call("e",q)
data = {'from':From,
'to':To,
'query':q,
'sign':sign,
'token':token}
text = requests.post(url,headers=headers,data=data).json()['trans_result']['data'][0]['dst']
print(text)

English abbreviation table of language

{
'zh': ' chinese ','jp': ' Japanese ','jpka': ' Japanese kana ','th': ' Thai, ','fra': ' French ','en': ' English ','spa': ' Spanish ','kor': ' Korean ','tr': ' Turkish language ','vie': ' Vietnamese ','ms': ' Malay Language ','de': ' German ','ru': ' Russian ','ir': ' Iranian ','ara': ' The Arabic language ','est': ' Estonian ','be': ' Belarusian ','bul': ' Bulgarian ','hi': ' Hindi ','is': ' Icelandic ','pl': ' Polish language ','fa': ' Persian ','dan': ' Danish language ','tl': ' Filipino ','fin': ' Finnish language ','nl': ' Dutch ','ca': ' Catalan ','cs': ' Czech ','hr': ' Croatian ','lv': ' Latvian ','lt': ' Lithuanian ','rom': ' romanian ','af': ' South African ','no': ' Norwegian ','pt_BR': ' Brazilian ','pt': ' Portuguese ','swe': ' Swedish language ','sr': ' Serbian ','eo': ' Esperanto ','sk': ' Slovak ','slo': ' Slovenian ','sw': ' Swahili ','uk': ' Ukrainian ','iw': ' Hebrew ','el': ' Greek ','hu': ' Hungarian ','hy': ' Armenian ','it': ' Italian ','id': ' Indonesian ','sq': ' albanian ','am': ' Amharic ','as': ' Assam ','az': ' Azerbaijani ','eu': ' Basque ','bn': ' Bengali ','bs': ' Bosnian ','gl': ' Galician ','ka': ' Georgian ','gu': ' Gujarati ','ha': ' Hausa ','ig': ' Ibo ','iu': ' Inuit ','ga': ' irish ','zu': ' Zulu ','kn': ' CA ad ','kk': ' kazakh ','ky': ' Kyrgyz ','lb': ' Luxemburg ','mk': ' Macedonian ','mt': ' Maltese ','mi': ' Maori ','mr': ' Malati ','ne': ' Nepali ','or': ' Oriya ','pa': ' Punjabi ','qu': ' Kachua ','tn': ' Seychellan ','si': ' Sengaro ','ta': ' Tamil language ','tt': ' Tatar ','te': ' Tai Lu Gu language ','ur': ' Urdu ','uz': ' Uzbek ','cy': ' Welsh ','yo': ' Yoruba ','yue': ' Cantonese ','wyw': ' classical Chinese ','cht': ' Chinese traditional ' }
版权声明
本文为[Tuffer tuffer]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database