Home  >  Article  >  Backend Development  >  How to use request library to implement translation interface in Python

How to use request library to implement translation interface in Python

王林
王林forward
2023-05-14 22:13:22845browse

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={
            '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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete