Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a song through python-requests

I was trying to make a script to download songs from internet. I was first trying to download the song by using "requests" library. But I was unable to play the song. Then, I did the same using "urllib2" library and I was able to play the song this time.

Can't we use "requests" library to download songs? If yes, how?

Code by using requests:

import requests
doc = requests.get("http://gaana99.com/fileDownload/Songs/0/28768.mp3")
f = open("movie.mp3","wb")
f.write(doc.text)
f.close()

Code by using urllib2:

import urllib2
mp3file = urllib2.urlopen("http://gaana99.com/fileDownload/Songs/0/28768.mp3")
output = open('test.mp3','wb')
output.write(mp3file.read())
output.close()
like image 350
Shivam Mitra Avatar asked Aug 24 '16 16:08

Shivam Mitra


People also ask

How do I download music using Python?

Looking to build projects on Python?: Download and install python latest version. Install spot-dl packages with the help of pip. Copy-paste the song or playlist link to download.

Is requests a library in Python?

The requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.

What is Python import requests?

Definition and Usage. The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).


1 Answers

Use doc.content to save binary data:

import requests

doc = requests.get('http://gaana99.com/fileDownload/Songs/0/28768.mp3')
with open('movie.mp3', 'wb') as f:
    f.write(doc.content)

Explanation

A MP3 file is only binary data, you cannot retrieve its textual part. When you deal with plain text, doc.text is ideal, but for any other binary format, you have to access bytes with doc.content.

You can check the used encoding, when you get a plain text response, doc.encoding is set, else it is empty:

>>> doc = requests.get('http://gaana99.com/fileDownload/Songs/0/28768.mp3')
>>> doc.encoding
# nothing

>>> doc = requests.get('http://www.example.org')
>>> doc.encoding
ISO-8859-1
like image 174
Tiger-222 Avatar answered Oct 22 '22 04:10

Tiger-222