一、运行的效果如下:

二、源码如下:
2 | from bs4 import BeautifulSoup |
7 | r = requests.get(url, timeout=30) |
11 | print ( "Get HTML Text Failed!" ) |
15 | def google_translate_EtoC(to_translate, from_language= "en" , to_language= "ch-CN" ): |
18 | url = base_url.format(to_language, from_language, to_translate) |
21 | html = getHTMLText(url) |
23 | soup = BeautifulSoup(html, "html.parser" ) |
27 | result = soup.find_all( "div" , { "class" : "t0" })[0].text |
29 | print ( "Translation Failed!" ) |
35 | def google_translate_CtoE(to_translate, from_language= "ch-CN" , to_language= "en" ): |
38 | url = base_url.format(to_language, from_language, to_translate) |
41 | html = getHTMLText(url) |
43 | soup = BeautifulSoup(html, "html.parser" ) |
47 | result = soup.find_all( "div" , { "class" : "t0" })[0].text |
49 | print ( "Translation Failed!" ) |
57 | inp = int(input( "Chinese to Englisth is 1, English to Chinese is 2: " )) |
59 | words = input( "请输入中文: " ) |
60 | print (google_translate_CtoE(words)) |
62 | words = input( "Please input English: " ) |
63 | print (google_translate_EtoC(words)) |
可参考的:
https://github.com/ssut/py-googletrans
https://github.com/terryyin/translate-python
https://github.com/yucongo/mgoogle_translate
updated on July-12-2020
三、写成一个类
3 | from bs4 import BeautifulSoup |
8 | html = requests.get(url) |
12 | json_data = json.loads(html) |
14 | # print (json_data[ 'data' ]) |
15 | for i in json_data[ 'data' ]: |
16 | # print ( "http://" +i[ 'ip' ]+ ":" +str(i[ 'port' ])) |
17 | ip = "http://" +i[ 'ip' ]+ ":" +str(i[ 'port' ]) |
23 | proxies = { "http" : proxy_ip } |
27 | def __init__(self, content, proxy): |
28 | self.content = content |
32 | def getHTMLText(self,url): |
34 | r = requests.get(url, proxies = self.proxy,timeout=30) |
39 | print ( "Get HTML Text Failed!" ) |
43 | def get_chinese_conetent(self,from_language= "en" , to_language= "ch-CN" ): |
46 | url = base_url.format(to_language, from_language, self.content) |
49 | html = self.getHTMLText(url) |
51 | soup = BeautifulSoup(html, "html.parser" ) |
55 | result = soup.find_all( "div" , { "class" : "t0" })[0].text |
57 | print ( "Translation Failed!" ) |
62 | def get_english_conetent(self,from_language= "ch-CN" , to_language= "en" ): |
65 | url = base_url.format(to_language, from_language, self.content) |
68 | html = self.getHTMLText(url) |
70 | soup = BeautifulSoup(html, "html.parser" ) |
74 | result = soup.find_all( "div" , { "class" : "t0" })[0].text |
76 | print ( "Translation Failed!" ) |
82 | a = "i love you very much" |
83 | c = Translate(a, proxies) |
84 | r = c.get_chinese_conetent() |
用法:
1 | from google_translate import Translate |
4 | ch_content = t2.get_chinese_conetent() |
四、注意事项
1.如果英文中有“&”这个符号,会影响翻译,就是到了&就断了,后面的句子不翻译。解决方案:
2 | content = content.replace( "#" , "" ) #这个符号也会造成翻译的问题 |
五、最新版本
https://github.com/lushan88a/google_trans_new/issues