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>

        教你用Python+PyQt5制作一款視頻數(shù)據(jù)下載小工具

        共 6130字,需瀏覽 13分鐘

         ·

        2020-11-25 07:40

        前言?

        目前,市場上有大量 Python圖形用戶界面(GUI)開發(fā)框架可供選擇,如wxpython 、pyqt5、Gtk、Tk等。

        本文將用Python結(jié)合PyQt5制作一款B站視頻數(shù)據(jù)下載器,可以通過輸入關鍵字、頁碼以及選擇存儲路徑后,下載相應的數(shù)據(jù),演示效果如下:


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

        Python3
        Pycharm
        PyQt5
        Qt Designer
        requests

        準備工作

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

        # -*- coding = uft-8 -*-
        # @Time : 2020-11-11
        # @Author : 「菜J學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 = {'標題': title, '播放量(萬)': click, '彈幕': danmu, '日期': date, 'UP主': up}
        with open('B站數(shù)據(jù).csv', 'a+', encoding='utf_8_sig', newline='') as fp:
        fieldnames = ['標題', '播放量(萬)', '彈幕', '日期', 'UP主']
        writer = csv.DictWriter(fp, fieldnames=fieldnames)
        writer.writerow(data)
        time.sleep(random.random() + 1)
        print('已經(jīng)完成b站第 {} 頁爬取'.format(i))

        if __name__ == "__main__":
        keyword = input("請輸入要搜索的關鍵詞:")
        page = int(input("請輸入要爬取的頁數(shù):"))
        get_target(keyword,page)

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


        UI設計

        這里用到一款好用的工具——Qt Designer,通過它用"鼠標拖拽"就能完成窗體設計。

        安裝Qt Designer

        pip3 install PyQt5
        pip3 install PyQt5-tools

        配置開發(fā)工具

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

        添加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)境,需要單獨安裝Qt,去官網(wǎng)下載開源版本即可。

        Qt Designer設計界面

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

        界面介紹

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

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

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

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

        界面操作

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

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

        界面設計好以后,保存為run.ui文件,選中“run.ui”,在其上點擊鼠標右鍵,到“External Tools”中點擊“PyUIC”,即可生成run.py文件:

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

        完善run.py,賦給“開始下載”按鈕以‘pushButton_click’函數(shù),賦給“存儲路徑”按鈕以‘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ù),導入接口url中,代碼如下:

        def pushButton_click(self):
        self.textEdit_4.setText("下載中......")
        self.keyword = self.lineEdit.text() #關鍵字
        self.page = int(self.lineEdit_2.text()) #頁數(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 = {'標題': 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 = ['標題', '播放量(萬)', '彈幕', '日期', 'UP主']
        writer = csv.DictWriter(fp, fieldnames=fieldnames)
        writer.writerow(data)
        self.textEdit_4.append("第{0}頁下載完成".format(i))
        self.textEdit_4.append("保存路徑:{}".format(self.download_path))
        self.textEdit_4.append( "文件名稱:{}".format('{0}共{1}個視頻數(shù)據(jù).csv'.format(self.keyword,self.page*20)))

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

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

        工具打包

        在cmd控制臺使用cd進入py文件所在目錄:

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

        使用pyinstaller打包:

        pyinstaller -F -w bilibili.py

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


        -END-

        往期精彩推薦 --??

        -- 1、在線代碼編輯器,可以分享給任何人
        -- 2、Python 造假數(shù)據(jù),用Faker就夠了
        -- 3、在Python中玩轉(zhuǎn)Json數(shù)據(jù)



        --? 留下你的“在看”唄!


        瀏覽 30
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        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>
            国产女淫 | 亚洲午夜AV无码高潮片 | 午夜视频久久久 | 啪啪啪视频免费在线观看 | 少妇又紧又色又爽又刺激的视频 | 单亲与子性伦刺激对白 | 中文字幕一区在线 | 成人无码Cosplay福利H视频 | 国产乱国产乱老熟300网址 | 18禁白丝袜美女网站色大片免费看 |