Catalog
Ideas
The process
Code implementation
Code 1 ( A little wrong )
result
Code 2
result
On Baidu translation , Translate , Click on inspection F12, You can see the data transmission on the network , See the translation website in the background , We can disguise the baidu translation website at the front desk , Send the same data to the translation background , Then get the translation information transmitted back from the background . Baidu translation needs to send messages under the disguise , Pretend to be a browser . But Youdao translation doesn't need to pretend to be a browser .
First little translation
find POST
There is corresponding translation on the right POST
Get the website of background translation
Get request fields
from urllib import request,parse
import json
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/68.0.3440.75 Safari/537.36'}
content=input(' Please enter the content you want to translate :')
dict={'kw':content}# What needs to be translated
new_name=parse.urlencode(dict)# Transcoding
url='https://fanyi.baidu.com/sug'#url Connect
response=request.Request(url,headers=headers,data=bytes(new_name,encoding='utf-8'))# encapsulate
text=request.urlopen(response).read().decode('utf-8')# Crawl data
content=json.loads(text)
print(' Translation results :',content['data'][0])
At the time of realization , There will be problems beyond the boundary .
from urllib import request,parse
import json
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/68.0.3440.75 Safari/537.36'}
content=input(' Please enter the content you want to translate :')
dict={'kw':content}# What needs to be translated
new_name=parse.urlencode(dict)# Transcoding
url='https://fanyi.baidu.com/sug'#url Connect
response=request.Request(url,headers=headers,data=bytes(new_name,encoding='utf-8'))# encapsulate
text=request.urlopen(response).read().decode('utf-8')# Crawl data
content=json.loads(text)
print(' Translation results :',content['data'][:-1])
In order to solve the problem of code one beyond the boundary , I took the direct use -1 Do the index , Defines the final boundary .