我正在尝试学习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,但仍然不起作用(我的意思是脚本将运行,但它不会翻译这个词)。
有人知道怎么修吗? (对不起我英语不好)
如果你想检查的话,我做了这个脚本: 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))
行。下面是:
您将得到以下输出:
顺便说一句,你有点违反了谷歌的服务条款;如果你做的不仅仅是为了训练而编写一个小脚本,那就去查一下。
使用
requests
我强烈建议您尽可能远离urllib,并使用优秀的^{} 库,这将允许您在Python中有效地使用
HTTP
。是的,他们的文档不容易被发现。
你要做的是:
在谷歌云平台控制台中:
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或其他可用手段限制使用。
下面是代码:
相关问题 更多 >
编程相关推荐