


How to use request library to implement translation interface in Python
Basic use of the requests library
Installation
To use the requests library in Python, you first need to install it using pip. You can do this by running the following command in the terminal:
pip install requests
Using
Once the library is installed, you can use it to make HTTP requests. The following is an example of how to make a GET request:
import requests response = requests.get('https://www.baidu.com') print(response.text)
In this example, we import the requests library, and then use the get method to make a GET request to https://www.baidu.com. The server's response is stored in the response variable and we print the response text to the console.
You can also pass parameters to the get method to include query parameters in the request:
import requests params = {'key1': 'value1', 'key2': 'value2'} response = requests.get('https://www.example.com', params=params) print(response.url)
In this example, we pass a dictionary of query parameters to the params parameter of the get method. The generated URL will include query parameters and we print the URL to the console.
You can also use the post method to make a POST request:
import requests data = {'key1': 'value1', 'key2': 'value2'} response = requests.post('https://www.example.com', data=data) print(response.text)
In this example, we pass a dictionary of data to the data parameter of the post method. The data will be sent in the body of the request and we print the response text to the console.
Develop your own translation interface
Analyze Baidu translation
Open the Baidu translation address, then press F12
to open the developer mode and enter the translated content. Click Translate. Through the picture below, you can clearly see the requested address and requested parameters
Baidu Translation sends a post to https://fanyi.baidu.com/v2transapi In the request, only sign is constantly changing in the data sent. Searching v2transapi found that the sign field is encrypted through js through the data string you want to send.
Through Baidu Translation’s js
analysis, the key code for encryption is as follows:
Now that we have figured out the entire calling process, all parameters can be constructed by ourselves. This way you can write code.
Write the interface code
1. In order to prevent the request from failing, we need to imitate the browser request and add the request header to the request. We use the third-party library fake_useragent
, Randomly generate different User-Agent
. The key code is as follows:
from fake_useragent import UserAgent headers = {'User-Agent': UserAgent().random}
2. Generate sign
parameters. Since we cannot understand the encrypted js
code, we directly call the python
The third-party library executes the js
code. You need to install the execjs
library before using it. Execute the following code:
pip3 install PyExecJS
The method of using this library is also very simple. For example, we have already mentioned above I have extracted Baidu’s encrypted js
code, created a new js
file, and copied the content into it. The key code is as follows:
def generate_sign(self,query): try: if os.path.isfile("./baidu.js"): with open("./baidu.js", 'r', encoding="utf-8") as f: baidu_js = f.read() ctx = execjs.compile(baidu_js) return ctx.call('b', query) except Exception as e: print(e)
First read the js file into the cache, and then call the object through execjs
. Finally, the method in the js
file is executed by calling the call
method, where b
is the method corresponding to js
, and query
is the parameter of the b
method in js
.
After the call is successful, the return is as follows:
3. Get the token
value and observe the source code of the Baidu translation page and findtoken
is stored in the page, so we can get token
.
res = request.get("https://fanyi.baidu.com").content.decode() token = re.findall(r"token: '(.*)',", res, re.M)[0]
4. So far All the request parameters are now available, so we can start constructing the request. The core code is as follows:
url = 'https://fanyi.baidu.com/v2transapi' sign = generate_sign("你好") data = { "from": "zh", "to": 'en', "query": "你好", "transtype": "translang", "simple_means_flag": "3", "sign": sign, "token": self.token, "domain": "common" } res = requests.post( url=url, params={"from": "zh", "to": 'en'}, data=data, headers = { 'User-Agent': UserAgent().random, } ) res.json().get("trans_result").get("data")[0].get("dst")
After the request is successful, the following picture will be returned:
It is found through the actual call that not every request is successful, so it is necessary Make multiple requests, go through a loop operation, and jump out of the loop when it is clear and successful. The key code is as follows:
tryTimes = 0 try: while tryTimes < 100: res = self.session.post( url=url, params={"from": fromLan, "to": toLan}, data=data, ) if "trans_result" in res.text: break tryTimes += 1 return res.json().get("trans_result").get("data")[0].get("dst")
In this way, we have completed using the Baidu translation interface to make our own translation interface call. You can use Flask
or Fastapi
to develop API interfaces according to your own needs. Below are all codes
import requests import execjs import os import re import json from loguru import logger from fake_useragent import UserAgent class Baidu_translate: def __init__(self): self.session=request.Session() self.session.headers={ 'User-Agent': UserAgent( ).random, "Host":"fanyi.baidu.com", "X-Requested-With":"XMLHttpRequest", "sec-ch-ua":'"Not?A_Brand";="8","Chromium";v="108","Microsoft Edge";V="108", "sec-ch-ua-mobile":"?0", "Sec-Fetch-Dest":"document", "Sec-Fetch-Mode":"navigate", "Sec-Fetch-Site": "same-origin", "Sec-Fetch-User":"?1", "Connection":"keep-alive", } self.session.get("https://fanyi.baidu.com" ) res = self.session.get("https://fanyi.baidu.com").content.decode( ) self.token = re.findall(r"token: '(.*)',",res,re.M)[0] def generate_sign(self,query): try: if os.path.isfile("./baidu.js"): with open("./baidu.js",'r',encoding="utf-8") as f: baidu_js = f.read( ) ctx = execjs.compile(baidu_js) return ctx.call('b',query) except Exception as e: print(e) def lang_detect(self,src: str) -> str: url = "https://fanyi.baidu.com/langdetect" fromLan = self.session.post(url, data={"query": src}).json()["lan"] return fromLan def translate(self,query: str, tolan: str = "", fromLan: str = "") -> str: if fromLan == "": fromLan = self.lang_detect(query) if toLan == "": toLan = "zh" if fromLan != "zh" else "en" url = 'https://fanyi.baidu.com/v2transapi' sign = self.generate_sign(query) data = { "from" : fromLan, "to": toLan, "query": query, "transtype":"translang", "simple_means_flag":"3", "sign" : sign, "token": self.token, "domain":"common" } tryTimes = 0 try: while tryTimes < 100: res = self.session.post( url=url, params={"from": fromLan,"to": toLan}, data=data, ) if "trans_result" in res.text: break tryTimes +=1 return res.json().get("trans_result").get("data")[0].get("dst") except Exception as e: print(e) def test(): url ='https://fanyi.baidu.com/v2transapi' sign = generate_sign("你好") data = { "from":"zh", "to":' en', "query":"你好", "transtype":"translang", "simple_means_flag":"3", "sign": sign, "token": self.token, "domain": "common" } res = requests.post( url=url, params={"from": "zh","to":'en'}, data=data, headers = { 'User-Agent': UserAgent( ).random, } ) res .json() if _name__ == "__main__": baidu_tran = Baidu_Translate() sign = baidu_tran.generate_sign("你好")
The above is the detailed content of How to use request library to implement translation interface in Python. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools