1. 程式人生 > 實用技巧 >如何讓程式像人一樣的去批量下載歌曲?Python爬取付費歌曲

如何讓程式像人一樣的去批量下載歌曲?Python爬取付費歌曲

前言

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理。

今天來教大家一個自動化爬蟲的工具selenium

selenium

Selenium 是一個 Web 的自動化測試工具,最初是為網站自動化測試而開發的,就像玩遊戲用的按鍵精靈,可以按指定的命令自動操作。

Selenium 測試工具直接操控瀏覽器中,就像真正的使用者在操作一樣。Selenium 可以根據的指令,讓瀏覽器自動載入頁面,獲取需要的資料,甚至頁面截圖,或者判斷網站上某些動作是否發生等。

專案目標

今天的目標是爬取付費歌曲

受害者地址

http://tool.liumingye.cn/music/?page=homePage

先給大家看下效果

爬蟲程式碼

匯入工具

import time
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

解析網頁

開啟F12 開發者工具,不管三七二十一,先來一頓瞎分析~

哦豁~ 這裡面居然有資料介面,還是post請求,那這樣的話就咱們就看它的data引數,那裡有變化

driver = webdriver.Chrome(executable_path='chromedriver.exe', options=chrome_options)
# key_world = input('請輸入歌手名字:')
driver.get('http://tool.liumingye.cn/music/?page=searchPage')
driver.find_element_by_css_selector('#input').send_keys('張傑')
driver.find_element_by_css_selector('#search  button:nth-child(2) i').click()
def download(name, url):
    filename = 'C:\\Users\\Administrator\\Desktop\\音樂\\' + name + '.mp3'
    response = requests.get(url=url)
    with open(filename, mode='wb') as f:
        f.write(response.content)

def drop_down():
    """模擬人去滾動滑鼠向下瀏覽頁面"""
    for x in range(1, 20, 10):
        time.sleep(0.5)
        j = x / 10
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        driver.execute_script(js)


lis = driver.find_elements_by_css_selector('#player li')
f = 0
for li in lis:
    f += 1
    name = li.find_element_by_css_selector('.aplayer-list-title').text
    li.find_element_by_css_selector('.aplayer-list-download').click()
    down_url = driver.find_element_by_css_selector('#m-download > div > div > div.modal-body > div:nth-child(6) > div.input-group-append > a.btn.btn-outline-secondary.download').get_attribute('href')
    driver.find_element_by_css_selector('#m-download > div > div > div.modal-header > button').click()
    # time.sleep(1)
    download(name, down_url)
    print(name, down_url)
    if f % 10 == 0:
        drop_down()

執行程式碼後,效果如下