通过 python-requests 下载歌曲

Downloading a song through python-requests

我试图制作一个脚本来从互联网上下载歌曲。我首先尝试使用 "requests" 库下载这首歌。但是我无法播放这首歌。然后,我使用 "urllib2" 库做了同样的事情,这次我能够播放这首歌。

不能用"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()

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

使用doc.content保存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)

说明

MP3 文件只是二进制数据,您无法检索其 文本 部分。当你处理纯文本时,doc.text 是理想的,但对于任何其他二进制格式,你必须使用 doc.content.

访问字节

你可以检查使用的编码,当你get一个纯文本响应时,doc.encoding被设置,否则它是空的:

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

来自here的类似方式:

import urllib.request 
urllib.request.urlretrieve('http://gaana99.com/fileDownload/Songs/0/28768.mp3', 'movie.mp3')