[爬虫]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 %s\n' % 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('pause\n')
    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("quit\n")
        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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值