Python 萌新 - 實現 Markdown 圖片下載器

xietao3發表於2018-01-19

簡書支援打包下載所有文章功能,可以方便作者轉移或儲存。但是圖片不支援自動下載,最近在學Python,便寫了一個md圖片下載器。

目標

本人 Python 新手,歡迎大佬指點。本文主要是對原始碼進行解讀,期望實現以下目標:

  1. 一鍵下載所有Markdown檔案中的圖片,並儲存到本地。
  2. 圖片根據文章分類
  3. 簡單易用。

先上最終效果:

下載過程

下載完成

實現步驟

  1. 搜尋指定資料夾,找出資料夾及子檔案包含的md檔案。
  2. 匹配出md檔案中所有的圖片。
  3. 所有圖片非同步下載。
  4. 下載報告與GUI。
  5. Python 打包工具。

準備開工

1. 搜尋資料夾中md檔案

首先我們要根據使用者指定的資料夾,搜尋出該資料夾及其子資料夾中包含的md檔案,並將這些檔案的絕對路徑加到陣列當中。

class Directory(object):

    @classmethod
    def find_sub_path(cls, path):
        # 初始化一個空的文章列表
        article_list = []
        # 獲取該資料夾下的所以子檔案
        temp_files = os.listdir(path)
        # 遍歷子檔案
        for temp_file in temp_files:
            # 拼接該檔案絕對路徑
            full_path = os.path.join(path, temp_file)

            # 匹配.md檔案 
            if os.path.isfile(full_path) and os.path.splitext(full_path)[1] == ".md":
                # 如果是.md檔案 加入文章列表
                article = Article(full_path)
                article_list.append(article)
            # 如果是資料夾 進行遞迴繼續搜尋
            elif os.path.isdir(full_path):
                # 將子資料夾中的文章列表拼接到上級目錄的文章列表中
                article_list.extend(cls.find_sub_path(full_path))

        return article_list
複製程式碼

2. 匹配出md檔案中的圖片

為每一篇文章新建一個存放該文章中圖片的資料夾,然後利用正則匹配出該文章中的所以圖片,並儲存到圖片陣列中。

# 文章類

class Article(object):

    def __init__(self, path):
        # 文章的絕對路徑
        self.article_path = path
        # 拼接文章圖片下載後儲存的路徑
        self.article_pic_dir = path.replace(".md", "_Image")
        # 新建儲存文章圖片的資料夾
        self.mkdir_image_dir()
        # 開始搜尋圖片
        self.pic_list = self.find_pics(self.article_path)

    # 查詢圖片
    def find_pics(self, article_path):
        # 開啟md檔案
        f = open(article_path, 'r')
        content = f.read()
        pics = []

        # 匹配正則 match ![]()
        results = re.findall(r"!\[(.+?)\)", content)

        index = 0
        for result in results:
            temp_pic = result.split("](")
            # 將圖片加入到圖片陣列當中
            if len(temp_pic) == 2:
                pic = Picture(temp_pic[0], temp_pic[1], self.article_pic_dir, index)
                pics.append(pic)
            index += 1
        f.close()
        return pics

    # 新建圖片的儲存資料夾
    def mkdir_image_dir(self):
        # 如果該資料夾不存在 則新建一個
        if not os.path.exists(self.article_pic_dir):
            os.mkdir(self.article_pic_dir)
複製程式碼

3. 下載圖片

簡單地判斷了圖片是否有型別,拼接圖片的儲存路徑與命名。檢查圖片是否重複下載,檢查圖片連結是否合法,下載並且儲存圖片,同時做了下載失敗的處理和儲存失敗的處理,儲存了下載失敗的原因,以便後面生成報告。

# 圖片類
class Picture(object):

    def __init__(self, name, url, dir_path, index):
        # 該圖片順序下標  用於設定預設圖片名字
        self.index = index
        # 圖片名
        self.name = name
        # 圖片連結
        self.url = url
        # 圖片儲存路徑
        self.dir_path = dir_path
        # 圖片下載失敗原因
        self.error_reason = None

    # 開始下載
    def start_download_pic(self, download_pic_callback):
        pic_path = self.build_pic_name()

        # 已存在則不重複下載
        if os.path.exists(pic_path):
            print ('pic has existed:' + self.url)
            self.error_reason = "pic has existed:"
            download_pic_callback(self)
            return

        # 圖片連結字首不包含http
        if not self.url.startswith("http"):
            print ('pic has invalid url:' + self.url)
            self.error_reason = "pic has invalid url"
            download_pic_callback(self)
            return

        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
            'Cookie': 'AspxAutoDetectCookieSupport=1',
        }

        # 下載圖片
        request = urllib2.Request(self.url, None, header)
        try:
            response = urllib2.urlopen(request, timeout=10)
        # 下載失敗
        except Exception, error:
            print ('pic cannot download:' + self.url)
            self.error_reason = str(error)
            download_pic_callback(self)
            return

        # 儲存圖片
        try:
            fp = open(pic_path, 'wb')
            fp.write(response.read())
            fp.close()
        # 儲存失敗
        except IOError, error:
            print(error)
            self.error_reason = str(error)
            download_pic_callback(self)
            return
        
        # 下載完成回撥
        download_pic_callback(self)

    # 組裝圖片儲存命名
    def build_pic_name(self):
        # 剪去圖片連結後的引數
        pic_url = self.url.split("?")[0]
        
        # 獲取圖片格式字尾 如果沒有 預設jpg
        urls = pic_url.split(".")
        if len(urls) > 1:
            pic_type = urls[len(urls)-1]
        else:
            pic_type = "jpg"

        # 組裝圖片命名
        if self.name is not None and len(self.name) > 0:
            pic_name = self.name + "." + pic_type
        else:
            pic_name = "no_name_" + str(self.index) + "." + pic_type
        
        pic_path = os.path.join(self.dir_path, pic_name)
        return pic_path
複製程式碼

4. 下載報告與GUI

a. 本來 XTImageDownloaderGUI 應該分開,但是對 Tkinter 理解還有限,所以就直接寫,方便呼叫。

這部分程式碼主要是 選擇資料夾開始搜尋並下載 的 UI 及邏輯處理。

選擇資料夾

class XTImageDownloader(object):

    def __init__(self):
        # 資料
        self.download_error_list = []
        self.all_pic_count = 0
        self.current_pic_index = 0
        self.thread_lock = threading.Lock()
        self.search_button = None
        # 圖形介面相關
        self.root = Tk()
        self.root.title("XTImageDownloader")
        self.path = StringVar()
        self.title = StringVar()
        self.title.set("請選擇Markdown檔案所在資料夾")
        self.list_box = None
        Label(self.root, textvariable=self.title).grid(row=0, column=1)
        Label(self.root, text="資料夾路徑:").grid(row=1, column=0)
        Entry(self.root, textvariable=self.path).grid(row=1, column=1)
        Button(self.root, text="選擇路徑", command=self.select_path).grid(row=1, column=2)
        self.root.mainloop()

    # 選擇資料夾
    def select_path(self):
        self.path.set(tkFileDialog.askdirectory())
        # 使用者選中資料夾之後 顯示下載按鈕
        if self.path.get() != "":
            self.search_button = Button(self.root, text="開始搜尋並下載", command=self.start_search_dir)
            self.search_button.grid(row=2, column=1)
            return self.path

    # 開始搜尋資料夾 並且下載
    def start_search_dir(self):
        self.search_button['state'] = DISABLED
        self.search_button['text'] = "正在下載..."
        
        self.all_pic_count = 0
        self.current_pic_index = 0
        self.download_error_list = []
        # 獲取Markdown檔案列表
        article_list = Directory.find_sub_path(self.path.get())

        # 更新搜尋進度 重新整理UI
        for article in article_list:
            self.all_pic_count += len(article.pic_list)
        self.change_title(self.all_pic_count, self.current_pic_index)

        # 開始下載圖片
        for article in article_list:
            for pic in article.pic_list:
                # 開啟非同步執行緒下載圖片 並且傳入下載完成的回撥
                thread = threading.Thread(target=pic.start_download_pic, args=(self.download_pic_callback,))
                thread.start()
複製程式碼

b. 開啟非同步執行緒下載圖片,回撥函式作為入參傳入。

下載圖片

  // 非同步下載
  thread = threading.Thread(target=pic.start_download_pic,   args=(self.download_pic_callback,))
  thread.start()
複製程式碼

回撥函式更新 UI 告知下載進度,由於開啟了多執行緒,這裡需要加鎖,防止資源競爭。全部下載成功後生成報告。

    # 下載圖片完成後的回撥函式
    def download_pic_callback(self, pic):
        # 獲取執行緒鎖
        self.thread_lock.acquire()
        # 如果下載失敗 則儲存到失敗列表
        if pic.error_reason is not None and len(pic.error_reason) > 0:
            self.download_error_list.append(pic)

        self.current_pic_index += 1

        # 更新下載進度 重新整理UI
        print('finish:' + str(self.current_pic_index) + '/' + str(self.all_pic_count))
        self.change_title(self.all_pic_count, self.current_pic_index)

        # 全部下載成功 重新整理UI 生成失敗報告
        if self.all_pic_count == self.current_pic_index:
            self.search_button['text'] = "下載完成"
            self.print_error(self.download_error_list)

        # 釋放鎖
        self.thread_lock.release()

    # 更新下載進度 重新整理UI
    def change_title(self, total_num, current_num):
        self.title.set("已完成" + str(current_num) + "/" + str(total_num))
複製程式碼

c. 生成失敗報告,利用 list_box 來展示錯誤列表,並且新增了滑塊,可以滑動瀏覽。

    # 生成失敗列表
    def print_error(self, download_error_list):
        # python log
        print("-----------------------------------")
        print("some pic download failure:")
        for pic in download_error_list:
            print("")
            print("name:" + pic.name)
            print("url:" + pic.url)
            print("error_reason:" + pic.error_reason)

        Label(self.root, text="部分圖片下載失敗:").grid(row=4, column=1)

        # GUI
        # 新建listbox
        self.list_box = Listbox(self.root)
        for pic in download_error_list:
            self.list_box.insert(END, pic.url + " -> " + pic.error_reason)
        self.list_box.grid(row=5, column=0, columnspan=3, sticky=W+E+N+S)

        # 垂直 scrollbar
        scr1 = Scrollbar(self.root)
        self.list_box.configure(yscrollcommand=scr1.set)
        scr1['command'] = self.list_box.yview
        scr1.grid(row=5, column=4, sticky=W+E+N+S)
        # 水平 scrollbar
        scr2 = Scrollbar(self.root, orient='horizontal')
        self.list_box.configure(xscrollcommand=scr2.set)
        scr2['command'] = self.list_box.xview
        scr2.grid(row=6, column=0, columnspan=3, sticky=W+E+N+S)
複製程式碼

d. 最後貼上引用到的標準庫(Python 2.7):

  1. #!/usr/bin/env python# -*- coding:utf-8 -*-這兩行是為了支援中文。
  2. osos.path用於系統及檔案查詢。
  3. re 正則匹配。
  4. urllib2網路庫,用於下載圖片。
  5. TkintertkFileDialog是 GUI 庫。
  6. threading多執行緒庫。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import os.path
import re
import urllib2
from Tkinter import *
import tkFileDialog
import threading
複製程式碼

5. Python 打包工具

最終效果

這部分主要是講如何把 Python 指令碼打包打包成可以在 Mac 上執行的應用。

PyInstaller

[圖片上傳失敗...(image-fd72fe-1516382674300)]

PyInstaller 是一個打包工具,可以幫助你打包 Python 指令碼,生成應用。

安裝 PyInstaller

$ pip install pyinstaller
複製程式碼

打包後在dist資料夾中可找到可執行檔案

$ pyinstaller yourprogram.py
複製程式碼

生成 app

$ pyinstaller --onedir -y  main.spec
複製程式碼

py2app

py2app 也是打包工具,這裡只是簡單介紹一下,想要深入瞭解詳細內容可以自行搜尋。

切換到你的工程目錄下

$ cd ~/Desktop/yourprogram
複製程式碼

生成 setup.py 檔案

$ py2applet --make-setup yourprogram.py
複製程式碼

生成你的應用

$ python setup.py py2app
複製程式碼

DMG Canvas

DMGCanvas

DMG Canvas 可以將 Mac 應用打包成 DMG 映象檔案,並且傻瓜式操作。

總結

剛開始只是寫了很簡單的一部分功能,後來慢慢完善,逐漸才有了現在的樣子,在這個過程中學到了很多東西,包括 Python 中的 GUI 和多執行緒操作,如何生成應用程式。希望能對一部分人有所幫助。

最後貼上Demo,本人 Python 2.7 環境下執行的, Python 3以上是無法執行的。

相關文章