通过谷歌翻译翻译的Python脚本

Bur*_*ras 4 python urllib2 beautifulsoup google-translate

我正在尝试学习python,所以我决定编写一个可以使用谷歌翻译翻译的脚本.直到现在我写了这个:

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()
Run Code Online (Sandbox Code Playgroud)

而现在我被卡住了.我看不到它中的任何错误,但它仍然无效(我的意思是脚本将运行,但它不会翻译这个词).

有谁知道如何修理它?(抱歉我的英语不好)

mou*_*mou 8

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


Tho*_*zco 5

Google翻译旨在与GET请求一起使用,而不是POST请求.但是,如果您向请求添加任何数据,urrllib2将自动提交POST.

解决方案是使用查询字符串构造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 )
Run Code Online (Sandbox Code Playgroud)

您将获得以下输出:

<span id="result_box" class="short_text">
    <span title="word" onmouseover="this.style.backgroundColor='#ebeff9'" onmouseout="this.style.backgroundColor='#fff'">
        parola
    </span>
</span>
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你有点打破谷歌的服务条款; 如果你做的不仅仅是攻击一个用于训练的小脚本,那么请查看它们.

运用 requests

我强烈建议你尽可能远离urllib,并使用优秀的requests库,这将允许你有效地使用HTTPPython.


eiT*_*aVi 5

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

这就是你要做的:

  1. 在 Google Cloud Platform Console 中

    1.1进入Projects页面,选择或创建一个新项目

    1.2为您的项目启用计费

    1.3启用云翻译API

    1.4在您的项目中创建一个新的 API 密钥,确保通过 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
Run Code Online (Sandbox Code Playgroud)