最近百度總愛作一些破壞用戶信任度的事——文庫金幣變券、網盤限速,嚇得我趕忙想辦法把存在百度雲音樂中的歌曲下載到本地。python
http://yinyueyun.baidu.com/linux
可問題是雲音樂中並無批量下載,而上面我總共存了700多首音樂!git
所以:有必要寫一個腳本自動下載這些音樂了!!!github
自動下載歌曲有兩種方法:ide
因爲考慮到JS法須要分析網頁結構、尋找下載連接,工做量有點大,因而選擇用模擬鼠標點擊法!測試
在linux上我首先想到用python來作這件事。優化
用python使用鼠標點擊事件比較簡單,在github上有人開源了一個PyMouse模塊,簡單幾行代碼就能模擬鼠標!spa
https://github.com/pepijndevos/PyMouse/wiki/Documentationcode
該PyMouse有個簡單的DEMO:blog
1 # import the module 2 from pymouse import PyMouse 3 4 # instantiate an mouse object 5 m = PyMouse() 6 7 # move the mouse to int x and int y (these are absolute positions) 8 m.move(200, 200) 9 10 # click works about the same, except for int button possible values are 1: left, 2: right, 3: middle 11 m.click(500, 300, 1) 12 13 # get the screen size 14 m.screen_size() 15 # (1024, 768) 16 17 # get the mouse position 18 m.position() 19 # (500, 300)
所以,編寫一個能夠自動下載一頁歌曲(20首)的腳本以下:
該代碼所作的主要任務是點擊下載,而後再點擊肯定:
注:若是隻是兩次點擊如何解釋2一、22行代碼?
由於點擊下載以後,會有個選擇下載音質的彈框,音質有高、中、低三種,可是有些歌曲只有一種或兩種音質能夠選擇。這致使彈框的位置有所不一樣(肯定按鈕的位置也隨之不一樣),解決此問題一個「笨」方法是將可能區域都點一遍!
1 # import the module 2 from pymouse import PyMouse 3 from time import sleep 4 5 # instantiate an mouse object 6 m = PyMouse() 7 8 pos_x = 1120 9 pos_y = 302 10 pos_y_add = 38 11 one_page_lines = 20 12 13 select_button_x = 984 14 select_button_y = 550 15 16 sleep(2) 17 18 for i in range(0,one_page_lines): 19 m.click(pos_x,pos_y+i*38,1) 20 sleep(2) 21 for j in range(0,30): 22 m.click(select_button_x,select_button_y+j*5,1) 23 sleep(3) 24 print(i)
上面腳本能在網速良好狀況下將一頁的歌曲下載到本地,接下來天然想到的是模擬鼠標拖動(拖動slide bar,切換至下一頁20首歌曲)。
因而我嘗試寫一個模擬鼠標拖動的腳本作個測試:
1 # import the module 2 from pymouse import PyMouse 3 from time import sleep 4 5 # instantiate an mouse object 6 m = PyMouse() 7 8 pos_x = 1120 9 pos_y = 302 10 pos_y_add = 38 11 one_page_lines = 20 12 13 select_button_x = 984 14 select_button_y = 550 15 16 slide_x = 1915 17 slide_y = 312 18 slide_dis = 1 19 20 sleep(5) 21 for page in range(1,40): 22 m.press(slide_x,slide_y) 23 slide_y = slide_y + slide_dis 24 m.move(slide_x,slide_y) 25 m.release(slide_x,slide_y) 26 sleep(10) 27
理論上每次滑動slide bar歌曲list移動的距離是相同的,而實測發現存在沒有規律的偏差!
因爲第二節中下載歌曲的腳本鼠標點擊的start位置是固定的,所以一旦不能利用slide bar移動使歌曲列表剛好切到下一頁,就會致使下載腳本點擊事件點錯地方。
後續優化方向能夠利用圖像識別對slide bar移動進行校準~
:: 若是您以爲不錯,請推薦給更多人,幫助他們更快地解決實際問題中的坑~
@beautifulzzzz 智能硬件、物聯網,熱愛技術,關注產品 博客:http://blog.beautifulzzzz.com 園友交流羣:414948975