通过Google翻译进行翻译的Python脚本

问题描述

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 )

您将获得以下输出

<span id="result_Box" class="short_text">
    <span title="word" onmouSEOver="this.style.backgroundColor='#ebeff9'" onmouSEOut="this.style.backgroundColor='#fff'">
        parola
    </span>
</span>

顺便说一句,您有点违反Google的服务条款; 如果您要做的不只是破解一些用于训练的脚本,还可以研究它们。

使用 requests

我强烈建议您尽可能避免使用urllib,而应使用出色的requests库,该库将使您可以有效地HTTP与Python一起使用。

解决方法

我正在尝试学习python,因此我决定编写一个脚本,可以使用Google翻译来翻译某些内容。直到现在我写了这个:

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()

现在我被卡住了。我看不到其中的任何错误,但仍然无法正常工作(因为我的意思是脚本可以运行,但不会翻译该词)。

有谁知道如何修理它?(对不起,我英语不好)