繼前一篇,來補充自製一個小功能,讓這個程式會好用一些些。
爬蟲在爬的時候,看 console 的畫面空蕩蕩的,是不是會有一種莫名的空虛感,而且也不知道剩下多少還沒爬
所以這篇文章主要教大家怎麼做一個 Progress Bar,讓人可以知道爬蟲目前的進度!
其實 Python 也有套件可以直接用,但了解原理之後我覺得自己做並不難,而且可以依照自己的需求做設計,使用上也會比較有彈性。
所以~我們來動手做吧!
class ProgressBar:
    bar_string_fmt = "\rProgress: [{}{}] {:.2%} {}/{}"
    cnt = 0
    def __init__(self, total, bar_total=20):
        # task 的總數
        self.total = total
        # progress bar 的長度,可依個人喜好設定
        self.bar_total = bar_total
    def update(self, step=1):
        # 更新 progress bar 的進度
        total = self.total
        self.cnt += step
        # bar 的數量
        bar_cnt = (int((self.cnt/total)*self.bar_total))
        # 空白的數量
        space_cnt = self.bar_total - bar_cnt
        # 顯示 progress bar
        # "\r" 的意思代表 replace,print 出來的字串不會印在新的一行而是 replace 原本那行同個位置的字符
        # {:.2%},表示 format 進來的值會以百分比顯示,並只取到小數點後兩位
        progress = self.bar_string_fmt.format(
            "█" * bar_cnt,
            " " * space_cnt,
            self.cnt/total,
            self.cnt,
            total
        )
        print(progress, end="")
        
        percent = self.cnt/total
        # 100%
        if percent == 1:
            print("\n")
        elif percent >= 1:
            print("")
            
if __name__ == '__main__':
    # 測試
    total = 10000
    progress_bar = ProgressBar(total)
    for _ in range(total):
        # do something...
        progress_bar.update()
輸出(GIF):
bar_total = 30(靜態圖):
bar_total = 50(靜態圖):
我們把它套用在上一篇自動更新每日個股日成交資訊的爬蟲裡面。
稍微對 DailyPriceSpider 這個類別做一些修改,才能使用 Progress Bar。
要改的地方不多,重複的程式碼我就不放了 。
。
class DailyPriceSpider:
    def __init__(self, progress_bar=None):
        # 重複使用 TCP 連線
        self.req = requests.Session()
        self.url = "https://www.twse.com.tw/exchangeReport/STOCK_DAY"
        self.headers = self.req.headers
        # 偽裝 User-Agent
        ua = UserAgent()
        self.headers["User-Agent"] = ua.random
        # 加入 progress bar 這個類別
        if progress_bar:
            self.progress_bar = progress_bar
    # ...省略
    def scrape(self, date, stock_no, save_path=""):
        res = self.__get(date, stock_no)
        if save_path:
            res_text = res.text
            self.__save_file(res_text, save_path)
        # 更新 progress bar
        if self.progress_bar:
            self.progress_bar.update()
        return res
另外主程式的部分:
if __name__ == '__main__':
    # ...省略
    stock_info_list = stock_info_list_file.get("stock", [])
    # 加入 progress bar
    progress_bar = ProgressBar(len(stock_info_list))
    dps = DailyPriceSpider(progress_bar=progress_bar)
    # ...省略
這樣就能看到我們的爬蟲進度囉!
(靜態圖)
以上就是 Progress Bar 的教學!
那整個系列文也差不多到這邊結束囉!如果有任何疑慮的地方,還請多多指教!