我试图制作一个脚本来从互联网上下载歌曲。我首先尝试使用“请求”库下载这首歌。但是我无法播放这首歌。然后,我使用“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
访问字节。
你可以检查使用的编码,当你得到
纯文本响应时,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
关于python - 通过 python-requests 下载歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39128738/