python - 通过 python-requests 下载歌曲

标签 python httprequest urllib2

我试图制作一个脚本来从互联网上下载歌曲。我首先尝试使用“请求”库下载这首歌。但是我无法播放这首歌。然后,我使用“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/

相关文章:

python - 如何使用spark sql获取多个表

python - 如何显示多个地标和路径?

c# - 将十六进制字符串解析为以 10 为基数的长整数

python - 如何使用 Python 在我的 google fusion 表中插入一行

Python 2.7 (urllib2)。如何使用 SSL HTTPS 代理?

python - 使用rdb远程调试Celery

.net - 解决 "Received an unexpected EOF or 0 bytes from the transport stream"服务器端

Android 忽略 DefaultHttpClient 超时参数

json - 请求参数RefreshType格式不正确

python - 从字符串中取出空格,并用 “+”替换它们