我是靠谱客的博主 调皮海燕,最近开发中收集的这篇文章主要介绍[爬虫]Luoo客户端,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

使用Qt4库
从QLabel派生出一个HexLabel类,能够接受鼠标的操作,能够贴上图片。

用一个QProcess来维护播放的进程(调用mplayer)。

关键点:html页面的解析。
先从读入数据中包含所需的数据的行(在分行之前需要先decode(encoding="UTF-8"),因为下载下来的是二进制数据)
先用字符串的各种replace把数据行格式化。然后分成多行,每一行对应一个数据(一首歌的信息)。对于每一行把每个数据域分割开。把相邻两项分别作为索引和值存入dict中。

音乐结束之后会,QProcess的finish自动调用,需要重新start一个进程。

切换音乐的时候不需要start,只需要给mplayer发送一条loadfile消息。

在程序退出之前,必须先给mplayer发送quit消息。并且等待最多30秒钟再退出,以防mplayer变成僵尸进程


import urllib.request
import sys
import time
from PyQt4 import QtGui,QtCore

#Label with pictures which can be clicked and toggled
class HexLabel(QtGui.QLabel):
    def __init__(self,parent=None):
        super(HexLabel,self).__init__(parent)
        self.checked = False
        
    clicked = QtCore.pyqtSignal()
    toggled = QtCore.pyqtSignal(bool)
    mousemove = QtCore.pyqtSignal()
    
    def mousePressEvent(self,event):
        if event.button() == QtCore.Qt.LeftButton:
            self.clicked.emit()
            self.checked = not self.checked
            self.toggled.emit(self.checked)
    def mouseMoveEvent(self, event):
        self.mousemove.emit(event)
#Frame
class Widget(QtGui.QWidget):
    def __init__(self,parent=None):
        super(Widget,self).__init__()
        QtGui.QWidget.__init__(self,parent)
        #Download info from Luoo.net
        self.getinfo()
        #Init UI
        self.InitUI()
        #Create Songprocess
        self.songprocess = QtCore.QProcess()
        self.songprocess.finished.connect(self.finished)
        #Start Song
        self.nowtrack = 0
        self.songprocess.start('mplayer',['-slave','-quiet',self.info[self.nowtrack]['mp3']])
        self.update()
    def getinfo(self):
        self.info = list(dict())
        for line in urllib.request.urlopen('http://luoo.net/').read().decode(encoding='UTF-8').splitlines():
            #Locate the info line
            if 'fm-cover' in line:
                fmcov = urllib.request.urlopen(line[line.find('http://'):line.find('" class')]).read()
                with open("fmcover.jpg",mode="wb") as img_file:
                    img_file.write(fmcov)
                palette1 = QtGui.QPalette(self)
                palette1.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('fmcover.jpg')))
                self.setPalette(palette1)
                self.setAutoFillBackground(True)
            if 'volPlaylist' in line:
                #Handle with html page
                for tmp in line.replace('tvar volPlaylist = ','').replace('{','').replace('}','').replace('}','').replace('[','').replace(']','').replace(';','').replace('/','/').replace(',',':').replace(':"id','nid').replace('":"','^').replace('"','').splitlines():
                    tmp = tmp.split('^')
                    #Append info to the dictionary list
                    self.info.append(dict([tmp[i:i+2] for i in range(0,len(tmp),2)]))
                break
    def finished(self):
        self.nowtrack = self.nowtrack + 1
        if (self.nowtrack == len(self.info)):
            self.nowtrack = 0
        self.songprocess.start('mplayer',['-slave','-quiet',self.info[self.nowtrack]['mp3']])
        time.sleep(1)
        self.update()
    def InitUI(self):
        #Frame
        self.setWindowTitle('Luoo')        
        self.resize(400,220)
        self.center()
        #Cover
        self.cover = QtGui.QLabel(self)
        self.cover.setGeometry(10,10,200,200)
        self.cover.setPixmap(QtGui.QPixmap('cover.jpg').scaled(200, 200))
        #Play Button
        self.playbutton = HexLabel(self)
        self.playbutton.setGeometry(220,10,50,50)
        self.playbutton.setPixmap(QtGui.QPixmap('play.png'))
        self.playbutton.toggled.connect(self.play)
        #Next Button
        self.nextbutton = HexLabel(self)
        self.nextbutton.setGeometry(280,10,50,50)
        self.nextbutton.setPixmap(QtGui.QPixmap('next.png'))
        self.nextbutton.clicked.connect(self.next)
        #Previous Button
        self.prevbutton = HexLabel(self)
        self.prevbutton.setGeometry(340,10,50,50)
        self.prevbutton.setPixmap(QtGui.QPixmap('prev.png'))
        self.prevbutton.clicked.connect(self.prev)
        #Title Info Label
        self.titleinfo = QtGui.QLabel(self)
        self.titleinfo.setGeometry(220,70,170,20)
        #Artist Info Label
        self.artistinfo = QtGui.QLabel(self)
        self.artistinfo.setGeometry(220,100,170,20)
    def next(self):
        if (self.nowtrack == len(self.info)-1):
            return
        self.nowtrack = self.nowtrack + 1
        self.update()
    def song(self):
        #Play the current song via mplayer
        self.songprocess.write('loadfile %sn' % self.info[self.nowtrack]['mp3']) 
    def update(self):
        #Download and set the cover picture
        cov = urllib.request.urlopen(self.info[self.nowtrack]['poster']).read()
        with open("cover.jpg",mode="wb") as img_file:
            img_file.write(cov)
        self.cover.setPixmap(QtGui.QPixmap('cover.jpg').scaled(200, 200))
        #Display info about the song
        #Cut the label if it's too long
        artist = self.info[self.nowtrack]['artist']
        title = self.info[self.nowtrack]['title']
            #tmp = "%s - %s" % (self.info[self.nowtrack]['title'],self.info[self.nowtrack]['artist'])
        if (len(artist)>25):
            artist=artist[0:25]+'...'
        if (len(title)>25):
            title=title[0:25]+'...'
        self.artistinfo.setText('<p><span style=" font-size:10pt; font-weight:600;">'+artist+'</span></p>')
        self.titleinfo.setText('<p><span style=" font-size:12pt; font-weight:600; color:#55aaff;">'+title+'</span></p>')
    def prev(self):
        if (self.nowtrack == 0):
            return
        self.nowtrack = self.nowtrack - 1
        self.song()
        time.sleep(1)
        self.update()    
    def play(self,pause):
        #switch between the two picture
        if pause:
            self.playbutton.setPixmap(QtGui.QPixmap('pause.png'))
        else:
            self.playbutton.setPixmap(QtGui.QPixmap('play.png'))
        #send a signal
        self.songprocess.write('pausen')
    def center(self):
        #To move the window to the center
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2,(screen.height()-size.height())/2)
    def closeEvent(self,ev):
        #kill mplayer before quit 
        self.songprocess.write("quitn")
        self.songprocess.waitForFinished(msecs=30000)
        ev.accept() 

def main():
    app = QtGui.QApplication(sys.argv)
    frame = Widget()
    frame.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


最后

以上就是调皮海燕为你收集整理的[爬虫]Luoo客户端的全部内容,希望文章能够帮你解决[爬虫]Luoo客户端所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部