Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string + web url and receive the response using python [closed]

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.

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.

like image 809
oudouz Avatar asked Aug 29 '11 04:08

oudouz


People also ask

How do you send data to a url in Python?

The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.


1 Answers

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()
like image 120
neurotik Avatar answered Sep 18 '22 19:09

neurotik