要通过google trans翻译的Python脚本

2024-10-05 10:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习python,所以我决定编写一个脚本,可以使用google translate翻译一些东西。到目前为止我写的是:

import sys
from BeautifulSoup import BeautifulSoup
import urllib2
import urllib

data = {'sl':'en','tl':'it','text':'word'} 
request = urllib2.Request('http://www.translate.google.com', urllib.urlencode(data))

request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')
opener = urllib2.build_opener()
feeddata = opener.open(request).read()
#print feeddata
soup = BeautifulSoup(feeddata)
print soup.find('span', id="result_box")
print request.get_method()

现在我被困住了。我看不出里面有什么bug,但仍然不起作用(我的意思是脚本将运行,但它不会翻译这个词)。

有人知道怎么修吗? (对不起我英语不好)


Tags: import脚本datarequestwindowsgoogleitopener
3条回答

如果你想检查的话,我做了这个脚本: https://github.com/mouuff/Google-Translate-API :)

Google translate用于GET请求,而不是POST请求。但是,如果向请求中添加任何数据,urrllib2将自动提交一个POST

解决方案是使用querystring构造url,这样您将提交一个GET
您需要更改代码的request = urllib2.Request('http://www.translate.google.com', urllib.urlencode(data))行。

下面是:

querystring = urllib.urlencode(data)
request = urllib2.Request('http://www.translate.google.com' + '?' + querystring )

您将得到以下输出:

<span id="result_box" class="short_text">
    <span title="word" onmouseover="this.style.backgroundColor='#ebeff9'" onmouseout="this.style.backgroundColor='#fff'">
        parola
    </span>
</span>

顺便说一句,你有点违反了谷歌的服务条款;如果你做的不仅仅是为了训练而编写一个小脚本,那就去查一下。

使用requests

我强烈建议您尽可能远离urllib,并使用优秀的^{}库,这将允许您在Python中有效地使用HTTP

是的,他们的文档不容易被发现。

你要做的是:

  1. 在谷歌云平台控制台中:

    1.1Go to the Projects page and select or create a new project

    1.2Enable billing for your project

    1.3Enable the Cloud Translation API

    1.4 Create a new API key in your project,确保通过IP或其他可用手段限制使用。


  1. 在要运行客户端的计算机中:

    pip install --upgrade google-api-python-client


  1. 然后您可以编写此命令来发送翻译请求和接收响应:

下面是代码:

import json
from apiclient.discovery import build

query='this is a test to translate english to spanish'
target_language = 'es'

service = build('translate','v2',developerKey='INSERT_YOUR_APP_API_KEY_HERE')

collection = service.translations()

request = collection.list(q=query, target=target_language)

response = request.execute()

response_json = json.dumps(response)

ascii_translation = ((response['translations'][0])['translatedText']).encode('utf-8').decode('ascii', 'ignore')

utf_translation = ((response['translations'][0])['translatedText']).encode('utf-8')

print response
print ascii_translation
print utf_translation

相关问题 更多 >

    热门问题