前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
很多人學習python,不知道從何學起,
很多人學習python,掌握了基本語法過后,不知道在哪里尋找案例上手,
很多已經做案例的人,卻不知道如何去學習更加高深的知識,
那么針對這三類人,我給大家提供一個好的學習平臺,免費領取視頻教程,電子書籍,以及課程的源代碼!??¤
QQ群:961562169
相關環境配置
- python 3.6
- pycharm
- requests
- parsel
相關模塊可pip安裝,如果覺得安裝速度太慢點擊下面鏈接查看相關教程
PIP安裝模塊失敗或者速度慢教程

?
請求網頁
import requests
url = 'http://sc.chinaz.com/yinxiao/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
print(response.text)

?
但是回傳資料有中文亂碼,編碼出現了問題,所以咱們只需要轉碼一下就可以了
response.encoding = response.apparent_encoding

?
決議資料
import parsel
selector = parsel.Selector(response.text)
urls = selector.css('#musiclist .n1::attr(thumb)').getall()
titles = selector.css('#musiclist .z a::attr(alt)').getall()
data = zip(urls, titles)
for i in data:
print(i)

?
保存資料
response_2 = requests.get(url=download_url, headers=headers)
filename = '路徑' + title + '.mp3'
with open(filename, mode='wb') as f:
f.write(response_2.content)

?
一頁的音頻檔案就都保存到本地檔案了
多頁爬取音頻檔案代碼
import requests
import parsel
for page in range(1, 603):
url = 'http://sc.chinaz.com/yinxiao/index_{}.html'.format(page)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
response.encoding = response.apparent_encoding
selector = parsel.Selector(response.text)
urls = selector.css('#musiclist .n1::attr(thumb)').getall()
titles = selector.css('#musiclist .z a::attr(alt)').getall()
data = zip(urls, titles)
for i in data:
print(i)
download_url = i[0]
title = i[1]
response_2 = requests.get(url=download_url, headers=headers)
filename = '路徑' + title + '.mp3'
with open(filename, mode='wb') as f:
f.write(response_2.content)

?
每頁40個檔案,一共是602頁資料,一共大概是2W多個音頻檔案素材,這邊咱們就不等了就下載了一千多個檔案,主要下載多了也占硬碟記憶體~ 代碼還是有很多可以優化的地方~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/173124.html
標籤:Python
