Dragon-TAO
2021-03-21 16:34
采纳率: 100%
浏览 113
已结题

为啥爬取下来的音乐大小都是1kb,打开说格式错误或者文件已经损坏

import requests
from bs4 import BeautifulSoup
from lxml import etree #用来预处理

#请求数据
url = 'https://music.163.com/discover/toplist?id=19723756'
#伪装自己
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.1071 SLBChan/21',
    'referer': 'https://music.163.com/'
}
response = requests.get(url=url,headers=headers,params=False).content.decode("utf-8")

s = BeautifulSoup(response, 'lxml')
main = s.find('ul', {'class': 'f-hide'})
list= main.find_all("a")


for i in list:

    name = i.text
    music_url = 'http://music.163.com/song/media/outer/url' + i['href'][5:] + '.mp3'
    music = requests.get(music_url).content
    with open('D:/NBA/'+name + '.mp3', mode='wb') as file:
        file.write(music)


  • 好问题 提建议
  • 收藏

1条回答 默认 最新

  • 我不喜欢这个世界 2021-03-21 22:04
    已采纳
    import requests
    from bs4 import BeautifulSoup
    from lxml import etree #用来预处理
    
    #请求数据
    url = 'https://music.163.com/discover/toplist?id=19723756'
    #伪装自己
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.1071 SLBChan/21',
        'referer': 'https://music.163.com/'
    }
    response = requests.get(url=url,headers=headers,params=False).content.decode("utf-8")
    
    s = BeautifulSoup(response, 'lxml')
    main = s.find('ul', {'class': 'f-hide'})
    list= main.find_all("a")
    
    for i in list:
        name = i.text
        music_url = 'http://music.163.com/song/media/outer/url' + i['href'][5:] + '.mp3'
        response = requests.get(music_url,headers=headers,allow_redirects=False)
        url = response.headers.get('Location')
        music = requests.get(url,headers=headers).content
        with open('D:/NBA/' + name + '.mp3', mode='wb') as file:
            file.write(music)
        
    
    

    请求中有重定向,禁止以后,再次访问重定向的链接就行了

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题