1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        實(shí)戰(zhàn)|教你用Python+PyQt5制作一款視頻數(shù)據(jù)下載小工具!

        共 6123字,需瀏覽 13分鐘

         ·

        2020-11-16 16:18

        前言

        大家好,我是早起。?

        目前,市場(chǎng)上有大量 Python圖形用戶界面(GUI)開發(fā)框架可供選擇,如wxpython 、pyqt5、Gtk、Tk等。本文將用Python結(jié)合PyQt5制作一款B站視頻數(shù)據(jù)下載器,可以通過輸入關(guān)鍵字、頁(yè)碼以及選擇存儲(chǔ)路徑后,下載相應(yīng)的數(shù)據(jù),演示效果如下:



        以下將詳細(xì)介紹這個(gè)GUI工具的制作方法,如需本文完整代碼,可以在公眾號(hào)「早起Python」后臺(tái)回復(fù)1116獲取。

        開發(fā)環(huán)境

        Python3
        Pycharm
        PyQt5
        Qt Designer
        requests

        準(zhǔn)備工作

        首先,新建一個(gè)bilibili.py文件。獲取B站視頻數(shù)據(jù)的爬蟲代碼相對(duì)簡(jiǎn)單,只要設(shè)置好url的keyword和page參數(shù),即可輕松獲取數(shù)據(jù)。以下貼出完整代碼:

        # -*- coding = uft-8 -*-
        # @Time : 2020-11-11
        # @Author : 「菜J學(xué)Python」J哥

        import requests
        from lxml import etree
        import time
        import random
        import csv

        def get_target(keyword,page):
        for i in range(1,page + 1):
        headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
        url = 'https://search.bilibili.com/all?keyword={0}&from_source=nav_suggest_new0&page={1}'.format(keyword,page)
        html = requests.get(url.format(i),headers = headers)
        bs = etree.HTML(html.text)
        items = bs.xpath('//li[@class = "video-item matrix"]')
        for item in items:
        title = item.xpath('div[@class = "info"]/div/a/@title')[0]
        click = item.xpath('div[@class = "info"]/div[3]/span[1]/text()')[0].strip('\n ').replace("萬","")
        danmu = item.xpath('div[@class = "info"]/div[3]/span[2]/text()')[0].strip('\n ')
        date = item.xpath('div[@class = "info"]/div[3]/span[3]/text()')[0].strip('\n ')
        up = item.xpath('div[@class = "info"]/div[3]/span[4]/a/text()')[0].strip('\n ')
        data = {'標(biāo)題': title, '播放量(萬)': click, '彈幕': danmu, '日期': date, 'UP主': up}
        with open('B站數(shù)據(jù).csv', 'a+', encoding='utf_8_sig', newline='') as fp:
        fieldnames = ['標(biāo)題', '播放量(萬)', '彈幕', '日期', 'UP主']
        writer = csv.DictWriter(fp, fieldnames=fieldnames)
        writer.writerow(data)
        time.sleep(random.random() + 1)
        print('已經(jīng)完成b站第 {} 頁(yè)爬取'.format(i))

        if __name__ == "__main__":
        keyword = input("請(qǐng)輸入要搜索的關(guān)鍵詞:")
        page = int(input("請(qǐng)輸入要爬取的頁(yè)數(shù):"))
        get_target(keyword,page)

        比如keyword輸入"打工人",page輸入5,運(yùn)行爬蟲代碼,即可生成打工人相關(guān)的B站視頻數(shù)據(jù)csv文件,數(shù)據(jù)預(yù)覽如下:


        UI設(shè)計(jì)

        這里用到一款好用的工具——Qt Designer,通過它用"鼠標(biāo)拖拽"就能完成窗體設(shè)計(jì)。

        安裝Qt Designer

        pip3 install PyQt5
        pip3 install PyQt5-tools

        配置開發(fā)工具

        安裝完Qt Designer后,我們利用PyCharm進(jìn)行界面開發(fā),下面進(jìn)行Qt開發(fā)工具的配置:Files —> Settings —> Tools —> External Tools —> 點(diǎn)擊"+"

        添加QT Desinger
        Name: QT Designer
        Program: designer.exe所在的路徑 # 注意:該路徑為你Python安裝路徑下Lib\site-packages\pyqt5_tools文件夾里
        Working directory: $FileDir$
        添加Py UIC
        Name: Py UIC
        Program: pyuic5.exe所在路徑 #該路徑為你Python安裝路徑下Scripts文件夾里
        Arguments: $FileName$ -o $FileNameWithoutExtension$.py;Working directory: $FileDir$

        注:如果是mac環(huán)境,需要單獨(dú)安裝Qt,去官網(wǎng)下載開源版本即可。

        Qt Designer設(shè)計(jì)界面

        在PyCharm中創(chuàng)建一個(gè)項(xiàng)目,然后點(diǎn)擊“Tools”--“External Tools”--“QT Desinger”打開QT Desinger,如下圖:

        界面介紹

        工具箱區(qū)域:提供GUI界面開發(fā)使用的各種基本控件,如單選框、文本框等??梢酝蟿?dòng)到新 創(chuàng)建的主程序界面。

        主界面區(qū)域:用戶放置各種從工具箱拖過來的各種控件。模板選項(xiàng)中最常用的就是 Widget(通用窗口)。

        對(duì)象查看器區(qū)域:查看主窗口放置的對(duì)象列表。屬性編輯器區(qū)域: 提供對(duì)窗口、控件、布局的屬性編輯功能。比如修改控件的顯示文本、對(duì) 象名、大小等。

        信號(hào)/槽編輯器區(qū)域:編輯控件的信號(hào)和槽函數(shù),也可以添加自定義的信號(hào)和槽函數(shù)。

        界面操作

        本文以創(chuàng)建Widget窗口為例,通過簡(jiǎn)單的拖拽,字體和顏色的配置,即可輕松完成如下界面的設(shè)計(jì):

        將ui文件轉(zhuǎn)為py代碼

        界面設(shè)計(jì)好以后,保存為run.ui文件,選中“run.ui”,在其上點(diǎn)擊鼠標(biāo)右鍵,到“External Tools”中點(diǎn)擊“PyUIC”,即可生成run.py文件:

        爬蟲代碼與界面相結(jié)合

        完善run.py,賦給“開始下載”按鈕以‘pushButton_click’函數(shù),賦給“存儲(chǔ)路徑”按鈕以‘setBrowerPath’函數(shù):

        self.pushButton.clicked.connect(Form.pushButton_click)
        self.pushButton_2.clicked.connect(Form.setBrowerPath)

        完善爬蟲代碼,將界面整體框架融入其中:

        import sys
        from run import Ui_Form #繼承run.py
        from PyQt5.QtWidgets import *
        from PyQt5 import QtCore, QtGui, QtWidgets

        class MyPyQT_Form(QWidget, Ui_Form):
        def __init__(self):
        super(MyPyQT_Form, self).__init__()
        self.setupUi(self)

        def pushButton_click(self):
        ······
        def setBrowerPath(self):
        ······

        if __name__ == '__main__':
        app = QApplication(sys.argv)
        my_pyqt_form = MyPyQT_Form()
        my_pyqt_form.show()
        sys.exit(app.exec_())

        然后在pushButton_click函數(shù)中添加代碼, 接收界面輸入的keyword和page參數(shù),導(dǎo)入接口url中,代碼如下:

        def pushButton_click(self):
        self.textEdit_4.setText("下載中......")
        self.keyword = self.lineEdit.text() #關(guān)鍵字
        self.page = int(self.lineEdit_2.text()) #頁(yè)數(shù)
        #result = pd.DataFrame()
        for i in range(1,self.page + 1):
        time.sleep(random.random() + 0.5)
        headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
        url = 'https://search.bilibili.com/all?keyword={0}&from_source=nav_suggest_new0&page={1}'.format(self.keyword,self.page)
        html = requests.get(url.format(i),headers = headers)
        bs = etree.HTML(html.text)
        items = bs.xpath('//li[@class = "video-item matrix"]')
        for item in items:
        title = item.xpath('div[@class = "info"]/div/a/@title')[0]
        click = item.xpath('div[@class = "info"]/div[3]/span[1]/text()')[0].strip('\n ').replace("萬","")
        danmu = item.xpath('div[@class = "info"]/div[3]/span[2]/text()')[0].strip('\n ')
        date = item.xpath('div[@class = "info"]/div[3]/span[3]/text()')[0].strip('\n ')
        up = item.xpath('div[@class = "info"]/div[3]/span[4]/a/text()')[0].strip('\n ')
        data = {'標(biāo)題': title, '播放量(萬)': click, '彈幕': danmu, '日期': date, 'UP主': up}
        with open('{0}/{1}視頻數(shù)據(jù).csv'.format(self.download_path,self.keyword),'a+', encoding='utf_8_sig', newline='') as fp:
        fieldnames = ['標(biāo)題', '播放量(萬)', '彈幕', '日期', 'UP主']
        writer = csv.DictWriter(fp, fieldnames=fieldnames)
        writer.writerow(data)
        self.textEdit_4.append("第{0}頁(yè)下載完成".format(i))
        self.textEdit_4.append("保存路徑:{}".format(self.download_path))
        self.textEdit_4.append( "文件名稱:{}".format('{0}共{1}個(gè)視頻數(shù)據(jù).csv'.format(self.keyword,self.page*20)))

        充實(shí)setBrowerPath函數(shù),獲取數(shù)據(jù)存儲(chǔ)路徑,將路徑在輸出框顯示出來:

        def setBrowerPath(self):
        self.download_path = QFileDialog.getExistingDirectory(self)
        self.textEdit_3.setText(self.download_path)

        工具打包

        在cmd控制臺(tái)使用cd進(jìn)入py文件所在目錄:

        cd D:\菜J學(xué)Python\GUI工具\(yùn)B站視頻數(shù)據(jù)下載器

        使用pyinstaller打包:

        pyinstaller -F -w bilibili.py

        運(yùn)行完成后,會(huì)在當(dāng)前目錄下生成1個(gè)dist文件夾和build文件夾,打開dist文件夾,雙擊bilibili.exe,工具即可運(yùn)行。如果是mac環(huán)境可以使用py2app進(jìn)行打包。

        -END-



        掃碼添加早小起,進(jìn)入Python技術(shù)交流群


        瀏覽 43
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            婬片A片AAA毛片妓女免费观看 | 啪啪在线 | 欧美三级片视频 | 巨胸喷奶水www免费看网站软件 | 亚洲AV大片 | 精品久久久久久久久久久久久久久久 | 国产成人无码视频免费手机在线播放 | 免费一级a毛片免费观看欧美大片 | 国产无码小视频 | 瑞典性xxxxxhd高清 |