headers需要進行修改,headers設置不對會被屏蔽導致爬取不成功。一個headers用久了也會爬取不成功
import os
from lxml import etree
import requests
# 設置頭部信息,防止被檢測出是爬蟲
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
url = "https://music.163.com/discover/toplist?id=3778678"
base_url = 'http://music.163.com/song/media/outer/url?id='
# 新建一個字典用於存儲最終所需要的數據
d = dict()
re = requests.get(url=url, headers=headers).text
# 構造了一個XPath解析對象並對HTML文本進行自動修正
html = etree.HTML(re)
# XPath使用路徑表達式來選取
x = html.xpath('//a[contains(@href,"/song?")]')
# 對取到的數據進行篩選
for data in x:
# 獲取到音樂url
href = data.xpath('./@href')[0]
id = href.split("=")[1]
href = base_url + "%s.mp3" % id
# 添加到字典
if "$" not in id:
# 獲得到標籤內的文本(即音樂的名稱)
name = data.xpath('./text()')[0]
d[href] = name
for i in d:
# 文件夾不存在,則創建文件夾
save_path = './music'
folder = os.path.exists(save_path)
if not folder:
os.makedirs(save_path)
# 下載音樂到當前目錄的music文件夾下
get = requests.get(base_url + '%s.mp3' % i, headers=headers).content
with open('./music/%s.mp3' % d[i], "wb") as f:
print("正在下載歌曲 《%s》 ..." % d[i])
f.write(get)