search
HomeBackend DevelopmentPython TutorialHow 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

How to use request library to implement translation interface in Python

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.

How to use request library to implement translation interface in Python

Through Baidu Translation’s js analysis, the key code for encryption is as follows:

How to use request library to implement translation interface in Python

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:

How to use request library to implement translation interface in Python

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.

How to use request library to implement translation interface in Python

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:

How to use request library to implement translation interface in Python

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={
            &#39;User-Agent&#39;: UserAgent( ).random,
            "Host":"fanyi.baidu.com",
            "X-Requested-With":"XMLHttpRequest",
            "sec-ch-ua":&#39;"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: &#39;(.*)&#39;,",res,re.M)[0]
        
    def generate_sign(self,query):
        try:
            if os.path.isfile("./baidu.js"):
                with open("./baidu.js",&#39;r&#39;,encoding="utf-8") as f:
                    baidu_js = f.read( )
            ctx = execjs.compile(baidu_js)
            return ctx.call(&#39;b&#39;,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 = &#39;https://fanyi.baidu.com/v2transapi&#39;
       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 =&#39;https://fanyi.baidu.com/v2transapi&#39;
    sign = generate_sign("你好")
    data = {
        "from":"zh",
        "to":&#39; en&#39;,
        "query":"你好",
        "transtype":"translang",
        "simple_means_flag":"3",
        "sign": sign,
        "token": self.token,
        "domain": "common"
        }
    res = requests.post(
        url=url,
        params={"from": "zh","to":&#39;en&#39;},
        data=data,
        headers = {
            &#39;User-Agent&#39;: 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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

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.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

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.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

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.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

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.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

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 vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

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.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

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 vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools