如何使用python +传递字符串和网址并接收响应 [英] How to pass a string + web url and receive the response using python
问题描述
我正在使用Python和Google Translate.当我在翻译时单击听"时,会生成一个声音文件,并像这样传递URL:http://translate.google.com/translate_tts?tl=en&q=text
.
I'm using Python and Google Translate. When I click on Listen while translating, a sound file is generated and a URL is passed like so: http://translate.google.com/translate_tts?tl=en&q=text
.
我想使用Python在本地生成URL,然后将其发送到网络并从Google Translate接收这些声音文件.我尝试了很多URLlib2和URLparse,但是我不知道我需要做些什么来使这项工作完成.
I want to generate URLs locally using Python then send them to the web and receive these sound files from Google Translate. I tried a lot of URLlib2 and URLparse but I have no clue about what I need to do to make this work.
推荐答案
您需要更改用户代理,以便网站认为您正在与浏览器连接.尝试以下代码:
You need to change the user-agent so that the website thinks you are connecting with a browser. Try the following bit of code:
import urllib2
url = "http://translate.google.com/translate_tts?tl=en&q=text"
request = urllib2.Request(url)
request.add_header('User-agent', 'Mozilla/5.0')
opener = urllib2.build_opener()
f = open("data.mp3", "wb")
f.write(opener.open(request).read())
f.close()
这篇关于如何使用python +传递字符串和网址并接收响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!