current position:Home>Baidu translation in Python
Baidu translation in Python
2022-07-24 16:31:30【Call me Ajie】
I hope it can be helpful to friends who are beginning to learn reptiles .
List of articles
- One 、 Analyze the web
- Two 、 Use steps
- 1. Import library
- 2. Keyboard input
- 3. structure url、headers and data Parameters
- 4. Initiate request , The response data
- 5. Analyze the data output results
- 3、 ... and 、 Complete code
One 、 Analyze the web
1. Open the web page , Enter Baidu translation in the search box and enter Baidu translation website .F12 Call up developer tools , Click on Network( The Internet )\ Fetch/XHR, At the same time, enter any search content in the translation box , At this point, you will find a name called sug My bag . Click the package , Click to see Heders、Payload、Preview and Rsponse Options such as . Click on Heders Options , take Request URL: The website at the back Copy , this Is what we need in our code url.
2. stay Heders Select the mouse wheel to the bottom , find User-Agent: And put the following parameters Copy , Namely What we need headers( Request header parameters ).
3. Click in the page Payload Options , stay Form Data Under the option, we Meeting notice Yes Parameters of key value pairs . Ahead ” key “ Equivalent to the search box in Baidu translation , The latter value is the translation content we entered . These parameters are data Parameters ,data Parameters are passed in a dictionary , So this ” key “ namely kw That's what we need data Key for parameter .
An exciting moment , Find the above parameters and you can go to the next step !!!
Two 、 Use steps
The code is as follows ( Example ):
import requests
import json
The code is as follows ( Example ):
fan_yi = input(" Please input the content to be translated :") # 2. Keyboard input translation
It's used here url Data requested by the network .
3. structure url、headers、data Parameters
Inside headers Parameters may report errors due to different devices , You can find the parameters of your computer browser according to the web page analysis above , Just copy it .
matters needing attention :headers Parameters exist in the form of dictionaries , Its keys and values are in string format , also User-Agent In the parameter U Letters and A All letters must be capitalized , If you write wrong carelessly, you will report an error .
The code is as follows ( Example ):
import requests # 1. Import library
import json
fan_yi = input(" Please input the content to be translated :") # 2. Keyboard input translation
url = "https://fanyi.baidu.com/sug" # 3. write in url
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 "} # 4. structure headers
data = {"kw":fan_yi} # 5. structure data
rsponse1 = requests.post(url = url,headers = headers,data = data) # 6. Initiate request
rsponse2 = rsponse1.text # Get response data
jie_xi = json.loads(rsponse2) # Parsing data
print(jie_xi) # Output results
4. Initiate request , The response data
The code is as follows ( Example ):
rsponse1 = requests.post(url = url,headers = headers,data = data) # Initiate request
rsponse2 = rsponse1.text # Get response data
5. Parsing data , Output results
The code is as follows ( Example ):
jie_xi = json.loads(rsponse2) # Parsing data
print(jie_xi) # Output results
3、 ... and 、 Complete code
matters needing attention :headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 "} In this part "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 " I have deleted it, so copying it directly will report an error , Because I found my computer browser according to the following figure User-Agent: The following parameters are copied into the code modify Talent .
Say important things three times !!!:headers Parameters exist in the form of dictionaries , Its keys and values are in string format , also User-Agent In the parameter U Letters and A All letters must be capitalized , If you write wrong carelessly, you will report an error .
Say important things three times !!!:headers Parameters exist in the form of dictionaries , Its keys and values are in string format , also User-Agent In the parameter U Letters and A All letters must be capitalized , If you write wrong carelessly, you will report an error .
Say important things three times !!!:headers Parameters exist in the form of dictionaries , Its keys and values are in string format , also User-Agent In the parameter U Letters and A All letters must be capitalized , If you write wrong carelessly, you will report an error .
Method 1 : Write in a proper manner
The code is as follows ( Example ):
import requests # Import library
import json
fan_yi = input(" Please input the content to be translated :") # Keyboard input translation
url = "https://fanyi.baidu.com/sug" # write in url
# structure headers
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 "}
data = {"kw":fan_yi} structure data
rsponse1 = requests.post(url = url,headers = headers,data = data) # Initiate request
rsponse2 = rsponse1.text # Get response data
jie_xi = json.loads(rsponse2) # Parsing data
print(jie_xi) # Output results
Method 2 : Encapsulate code into functions
def fangYi(data1):
url = "https://fanyi.baidu.com/sug"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64)
data = {"kw":data1}
rsponse1 = requests.post(url = url,headers = headers,data = data)
rsponse2 = rsponse1.content.decode()
json1 = json.loads(rsponse2)
print(json1)
if __name__ == '__main__':
while True:
data1 = input("+++++ Please enter the content to be translated below , Exit please enter ”no“+++++\n\t Please input the content to be translated :")
if data1 == "no":
break
else:
fangYi(data1)
copyright notice
author[Call me Ajie],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/205/202207241627583923.html
The sidebar is recommended
- Chinese garbled code in sublime Text3 compiling and running c++/java/python program language [solved]
- On the problem of Python: using numerical loops for cumulative calculation
- Pandas knowledge points - detailed grouping function groupby
- There is no network in the LAN. Use pip to install python3 plug-in
- Python 0x80070659 system policy prohibits this installation
- Python list parity split
- Python visual data analysis 01. Python environment construction
- Python visual data analysis 02. Scrapy framework - enhanced test scrapy CSS
- Python visual data analysis 03, Jieba [word segmentation]
- Image processing with Python opencv
guess what you like
Python AI tutorial Hagrid gesture recognition image data set (tutorial includes source code)
Python function parameter type summary
Function parameter passing in Python
Use of Python lists
Python sends simple SMTP mail
Application of sets in python (intersection and difference subsets, etc.)
Excuse me, I have opened a python 3.6 runtime FC. Without moving anything, the test function is directly executed
Zero threshold for career change and 100% employment? A group of young people are chasing Python
Python identification verification code - Google recapture 4*4 verification code
Python identification verification code - Google recapture 3*3 verification code
Random recommended
- Using the expansion of arctangent function to calculate the value of PI in Python
- Python01 - variables and simple data types
- Python excel cell data processing
- Pandas reading excel time field
- Pandas reads excel fields that contain characters beginning with 0
- HTTPS experience: introduction and use of basic cryptography knowledge and python pycrypto Library
- Python+vue COVID-19 vaccination management system Django project source code introduction
- Python image to character painting, with source code
- It is convenient to realize matrix transpose and inversion by using Python's unpacking and pressing methods
- Python error: typeerror,'int'object is not Iterable
- Python function comments appear: expected an indented block
- Python basic syntax - functions
- R language book learning 04 "implementation of multivariate statistical analysis R and python"
- Python word frequency analysis
- Docker series 4 dockerfile creates Python image
- Detailed explanation of Python's groupby() function
- Python scripting test cases
- Pyperclip module of Python -- copy and paste artifact
- Detailed explanation of Python · print output function
- [Python web] the use of Python to connect to third-party database series redis and redis
- [Python web] Python connection to third-party database series using pymongo to connect mongodb
- [Ubuntu operation] upgrade the default version of Python to python3.8 in Ubuntu 18.04.5
- [Python web] Python connects to third-party database series using pymysql to MySQL
- Python graphics development Kivy small problems
- Python tool method 33 easily realizes the integration of multiple losses based on the lossfusion class
- Summary of Python automated test interview questions (I) (continuously updated)
- Python office software automation, 5 minutes to master openpyxl operation
- Python interview question - [bisection search] given a sorted array of non repeating integers and a target value, if the target is found, the index is returned.
- Python test development django-197.django-celery-beat scheduled task
- Play with Python tips [i for I in range()] + [or]
- [leetcode scribble Python] 15. Sum of three numbers
- [leetcode scribble Python] 16. The sum of the nearest three numbers
- Python38 failed to install jsonpath. Problem solving
- Python test development django-193. use the supervisor background to start the celery service (worker/beat)
- Python test development django-194.addcomments module generates MySQL table field comments
- Python test development django-196.python 3.8 + django2 + celery5.2.7 environment preparation
- Python test development django-195.django add favicon.ico Icon
- [leetcode scribble Python] 122. The best time to buy and sell stocks II
- Common methods of saving pictures in Python
- Python word frequency analysis