简易Python Selenium爬虫实现歌曲免费下载

2017 年 10 月 29 日 凡人机器学习

再不点蓝字关注,机会就要飞走了哦

最近发现越来越多的歌曲下载都需要缴费了,对维护正版是好事。但有的时候也想钻个空子,正好最近在学习python,随手写了一个建议爬虫,用来爬取某播放软件的在线音乐。

主要思路就是爬取播放页里的播放源文件的url,程序可以读取用户输入并返回歌单,,,因为在线网站包含大量js,requests就显得很无奈,又懒得手动解析js,于是寄出selenium大杀器。

selnium是一款很强大的浏览器自动化测试框架,直接运行在浏览器端,模拟用户操作,目前selenium支持包括IE,Firefox,Chrome等主流浏览器及PhantomJS之类的无头浏览器,selenium+phantomjs也是现在很火的一个爬虫框架。

代码不长,做的有些简陋,以后可以加个GUI。。。。

步骤一:

进入酷狗主页,F12查看元素,,通过selenium.webdriver的send_keys()方法给send_input类传参,即用作用户的输入,然后通webdriver.click()方法点击搜索按钮,得到搜索结果列表。这里会有一个js重定向,通过webdriver.current_ur就可以了,,切记一点!传入的参数需要经过unicode编码(.decode(‘gb18030′))效果一样),否则如果有中文会乱码。。(来自被深深困扰的我)

步骤二:

查看元素里每首歌的路径,发现每首歌的路径只有<li>不同,于是通过对li的迭代来获取每一首歌的xpath,并输出歌曲名字的元素,然后依旧通过webdriver的click()方法点击歌曲链接,得到歌曲播放页面,这里没有什么难点,都是常规操作。需要注意的是,这里的歌曲链接也包含一个js的重定向,但不一样的是浏览器会打开一个新的页面(至少火狐会),可以在click()方法后通过webdriver.switch_to_window()方法跳转到新打开的页面

步骤三:

进入播放页面后通过xpath找到播放源文件链接(强推firepath,xpath神器啊)但发现这里依然有一个js渲染,来生成播放源链接,直接提取<src>标签会显示为空,于是继续webdriver,调用的浏览器会自动解析js脚本,解析完成后提取<src>得到歌曲链接,使用urllib的urlretrueve()下载即可

代码如下:

#coding=utf-8
from selenium.webdriver.remote.webelement import WebElement
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
import time
import urllib

#歌曲名
mname = ''

#JS重定向
def wait(driver):
    elem = driver.find_element_by_tag_name('html')
    count = 0
    while True:
        count += 1
        if count > 20:
            print('chao shi le')
            return
        time.sleep(.5)
        try:
            elem == driver.find_element_by_tag_name('html')
        except StaleElementReferenceException:
            return

#获取url
def geturl():
    input_string = raw_input('>>>please input the search key:')
    driver = webdriver.Chrome()
    url = 'http://www.kugou.com/'
    driver.get(url)
    a=driver.find_element_by_xpath('html/body/div[1]/div[1]/div[1]/div[1]/input') #输入搜索内容
    a.send_keys(input_string.decode('gb18030'))
    driver.find_element_by_xpath('html/body/div[1]/div[1]/div[1]/div[1]/div/i').click() #点击搜索
    result_url = driver.current_url
    driver.quit()
    return result_url


#显示搜索结果
def show_results(url):
    driver = webdriver.Chrome()
    driver.get(url)
    time.sleep(3)
    for i in range(1,1000):
        try:
            print '%d. '%i + driver.find_element_by_xpath(".//*[@id='search_song']/div[2]/ul[2]/li[%d]/div[1]/a"%i).get_attribute('title')  #获取歌曲名
        except NoSuchElementException as msg:
            break
    choice = input(">>>Which one do you want(you can input 'quit' to goback(带引号)):")
    if choice == 'quit':   #从下载界面退回
        result = 'quit'
    else:
        global mname
        mname = driver.find_element_by_xpath(".//*[@id='search_song']/div[2]/ul[2]/li[%d]/div[1]/a"%choice).get_attribute('title')
        a = driver.find_element_by_xpath(".//*[@id='search_song']/div[2]/ul[2]/li[%d]/div[1]/a"%choice)
        actions = ActionChains(driver)
        actions.move_to_element(a)
        actions.click(a)
        actions.perform()
        #wait(driver)
        driver.switch_to_window(driver.window_handles[1])  #跳转到新打开的页面
        result = driver.find_element_by_xpath(".//*[@id='myAudio']").get_attribute('src') #获取播放元文件url
        driver.quit()
    return result


#下载回调
def cbk(a, b, c):
    per = 100.0 * a * b / c  
    if per > 100:
        per = 100
    print '%.2f%%' % per
    

def main():
    print'***********************欢迎使用GREY音乐下载器********************************'
    print'                                                      directed by GreyyHawk'
    print'**************************************************************************'
    time.sleep(1)
    while True:
        url = geturl()
        result = show_results(url)
        if result == 'quit':
            print'\n'
            continue
        else:
            local = 'd://%s.mp3'%mname
            print 'download start'
            time.sleep(1)
            urllib.urlretrieve(result, local, cbk)
            print 'finish downloading %s.mp3'%mname + '\n\n'



if __name__ == '__main__':
  main()                         
     

效果:

总结:

当网页包含大量js的时候,selenium就会非常的方便,但经过实践发现好像phantomjs解析js的效率没有世纪浏览器的高,还会出错,后来换成调用火狐就好了,,不知道为啥,,也许是脸黑吧,,总之selenium真的是一款非常强大的框架,对爬虫有兴趣的同学一定要了解一下。


via 36大数据

欢迎投稿,来稿请发送:

tougao@fanrenyun.com


给我一分钟

送你一个学习的世界

微信号:凡人机器学习

长按二维码关注


登录查看更多
0

相关内容

XPath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言。XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力。起初 XPath 的提出的初衷是将其作为一个通用的、介于XPointer与XSLT间的语法模型。但是 XPath 很快的被开发者采用来当作小型查询语言。
一份简明有趣的Python学习教程,42页pdf
专知会员服务
76+阅读 · 2020年6月22日
【实用书】Python爬虫Web抓取数据,第二版,306页pdf
专知会员服务
115+阅读 · 2020年5月10日
【干货书】流畅Python,766页pdf,中英文版
专知会员服务
223+阅读 · 2020年3月22日
【资源】100+本免费数据科学书
专知会员服务
105+阅读 · 2020年3月17日
【电子书】Flutter实战305页PDF免费下载
专知会员服务
20+阅读 · 2019年11月7日
手把手教你用Python实现“坦克大战”,附详细代码!
机器学习算法与Python学习
11+阅读 · 2019年6月8日
一文看懂怎么用 Python 做数据分析
大数据技术
23+阅读 · 2019年5月5日
GitHub 热门:各大网站的 Python 爬虫登录汇总
机器学习算法与Python学习
9+阅读 · 2019年3月20日
抖音爬虫
专知
3+阅读 · 2019年2月11日
我是一个爬虫
码农翻身
12+阅读 · 2018年6月4日
干货 | Python 爬虫的工具列表大全
机器学习算法与Python学习
10+阅读 · 2018年4月13日
Python 爬虫实践:《战狼2》豆瓣影评分析
数据库开发
5+阅读 · 2018年3月19日
《小美好》短评文本情感分析+生成词云
数据挖掘入门与实战
5+阅读 · 2018年1月7日
教你用Python来玩跳一跳
七月在线实验室
6+阅读 · 2018年1月2日
SlowFast Networks for Video Recognition
Arxiv
19+阅读 · 2018年12月10日
Labeling Panoramas with Spherical Hourglass Networks
Arxiv
6+阅读 · 2018年7月29日
Arxiv
6+阅读 · 2018年2月7日
VIP会员
相关VIP内容
一份简明有趣的Python学习教程,42页pdf
专知会员服务
76+阅读 · 2020年6月22日
【实用书】Python爬虫Web抓取数据,第二版,306页pdf
专知会员服务
115+阅读 · 2020年5月10日
【干货书】流畅Python,766页pdf,中英文版
专知会员服务
223+阅读 · 2020年3月22日
【资源】100+本免费数据科学书
专知会员服务
105+阅读 · 2020年3月17日
【电子书】Flutter实战305页PDF免费下载
专知会员服务
20+阅读 · 2019年11月7日
相关资讯
手把手教你用Python实现“坦克大战”,附详细代码!
机器学习算法与Python学习
11+阅读 · 2019年6月8日
一文看懂怎么用 Python 做数据分析
大数据技术
23+阅读 · 2019年5月5日
GitHub 热门:各大网站的 Python 爬虫登录汇总
机器学习算法与Python学习
9+阅读 · 2019年3月20日
抖音爬虫
专知
3+阅读 · 2019年2月11日
我是一个爬虫
码农翻身
12+阅读 · 2018年6月4日
干货 | Python 爬虫的工具列表大全
机器学习算法与Python学习
10+阅读 · 2018年4月13日
Python 爬虫实践:《战狼2》豆瓣影评分析
数据库开发
5+阅读 · 2018年3月19日
《小美好》短评文本情感分析+生成词云
数据挖掘入门与实战
5+阅读 · 2018年1月7日
教你用Python来玩跳一跳
七月在线实验室
6+阅读 · 2018年1月2日
Top
微信扫码咨询专知VIP会员