程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses Baidu translation background for local translation

編輯:Python

Catalog

Ideas

The process

Code implementation

Code 1 ( A little wrong )

result

Code 2

result


Ideas

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 .

The process

First little translation

  find POST

There is corresponding translation on the right POST

 

Get the website of background translation

Get request fields

Code implementation

Code 1 ( A little wrong )

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 .

result

Code 2

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 .

result


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved