通过python或其他编程语言从Google网页获取翻译结果

时间:2018-09-21 13:12:25

标签: java c# php python google-translate

如何开发小型软件,只要指定URL(例如www.foxnews.com)和目标语言(例如中文),该软件就会自动调用google翻译结果。

url:www.foxnews.com

要求:

<html>
Translated web content
</html>

Google网页翻译API: https://translate.google.com/translate?sl=en&tl=zh-CN&js=y&prev=_t&hl=en&ie=UTF-8&u=www.foxnews.com&edit-text=&act=url 程序开发语言不受限制,例如python,php,c#,java等。

我用Python编写了一个小程序测试,但是效果不佳!

重用:

other code...
<iframe sandbox="allow-same-origin allow-forms allow-scripts allow-popups" src="https://translate.googleusercontent.com/translate_p?hl=en&rurl=translate.google.com&sl=auto&sp=nmt4&tl=zh-CN&u=http://www.foxnews.com/&depth=4&xid=25657,15700021,15700124,15700149,15700186,15700191,15700201,15700214&usg=ALkJrhgAAAAAW6Tq8NE5bkJZI9Rp_GhWRVSdEja6ZjXB" name=c frameborder="0" style="height:100%;width:100%;position:absolute;top:0px;bottom:0px;"></iframe>
other code...

翻译后的结果包含iframe,但我希望将翻译结果包含在iframe中。

#coding:utf-8
import os
import codecs       
import requests

  def write_file(filename, content, encoding='gbk', mode='a+'):
  dir_name = os.path.dirname(filename).strip()
  if os.path.exists(dir_name) is False:
    os.makedirs(dir_name)
    with codecs.open(filename=filename, mode=mode, encoding=encoding) as f:
    return f.write(content + '\r\n')

  if __name__ == "__main__":
    url = 'https://translate.googleusercontent.com/translate_p?hl=en&rurl=translate.google.com&sl=auto&sp=nmt4&tl=zh-CN&u=http://www.foxnews.com/&depth=3xid=25657,15700021,15700124,15700149,15700186,15700191,15700201,15700214&usg=ALkJrhgAAAAAW6SrzEpQsnIHKUKB7HmJz2Hr1IlZZbNC'
    r = requests.get(url=url)
    html = r.text
    write_file(filename='./a.html', content=html, mode='w', encoding='utf-8')

1 个答案:

答案 0 :(得分:2)

您需要为此使用Google Cloud。 Cloud Translation

编辑: 创建Google云帐户后,请使用此API进行翻译

POST https://translation.googleapis.com/language/translate/v2

documentation