Reference from: http://www.icourse163.org/learn/BIT-1001870001?tid=1001962001#/learn/forumdetail?pid=1003366321
Import requestsfrom BS4 import beautifulsoup def gethtmltext (URL): try:r = Requests.get (URL, timeout=30) R.raise_for_status () return r.text except:print ("Get HTML text failed!") return 0 def google_translate_etoc (to_translate, from_language= "en", to_language= "CH-CN"): #根据参数生产提交的网址 Base_url = " https://translate.google.cn/m?hl={}&sl={}&ie=utf-8&q={} "url = Base_url.format (To_language, From_ Language, to_translate) #获取网页 html = gethtmltext (URL) If Html:soup = BeautifulSoup (HTML, "Html.parse R ") #解析网页得到翻译结果 Try:result = Soup.find_all (" div ", {" Class ":" T0 "}) [0].text Except:print (" Translation failed! ") result = "" Return resultdef Google_translate_ctoe (to_translate, from_language= "CH-CN", to_language= "en"): #根据参数生产提交的网址 base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=utf-8&q={}" url = Base_url.format ( To_language, From_language,to_translate) #获取网页 html = gethtmltext (URL) If Html:soup = BeautifulSoup (HTML, "Html.parser") #解析网页得到翻译结果 Try:result = Soup.find_all ("div", {"Class": "T0"}) [0].text except:print ("Translatio n failed! ") result = "" Return Resultdef Main (): While true:inp = int (input ("Chinese-englisth is 1, 中文版 To Chinese is 2: ")) if InP = = 1:words = input (" Please enter Chinese: ") Print (Google_translate_ctoe ( words) Else:words = input ("Please input 中文版:") print (Google_translate_etoc (words)) m Ain ()
Python Google Translate API