【问题标题】:Downloading a song through python-requests通过 python-requests 下载歌曲
【发布时间】:2016-08-24 16:36:28
【问题描述】:

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

我们不能使用“请求”库来下载歌曲吗?如果是,怎么做?

使用请求编码:

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

【问题讨论】:

    标签: python httprequest urllib2


    【解决方案1】:

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

    【讨论】:

    • 你能解释一下使用二进制编码而不是unicode吗?
    • 我加了一点解释。
    【解决方案2】:

    类似here的方式:

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

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多