Python 練習之Baidu 圖片下載

# Time: 2020/05/08

#Author: Xiaohong

# 運行環境: OS: Windows 7

#  Python: 3.7

# 功能: 根據關鍵詞 key 到baidu 下載 pic_number 張的圖片

# https://www.jianshu.com/p/33bee611fa7d

# https://www.cnblogs.com/SeekHit/p/6284974.html

主界面如下:

主界面對應的程式如下:

# -*- coding:utf-8 -*-
import tkinter as tk
from tkinter.ttk import *
from tkinter import ttk
from Tl_class_frame import *
# from Tl_baidu_DownPic02 import *
from Tl_baidu_DownPic02  import *
import tkinter.messagebox
import os
import time
from tkinter.filedialog import askopenfilename

class Tl_baidu_DownPic02_screen(object):
    #設計UI 界面
    def setupUI(self):
        v = View(self.root, kind='日', orient=tk.HORIZONTAL)
        v.v1['height'] = 120

        # 設立LabelFrame
        lf1=tk.LabelFrame(v.v1,text='參數')
        lf1.pack(side=tk.LEFT,ipadx=60,ipady=20)

        # #增加Label,用來        
        tk.Label(lf1,text='要下載在內容').pack(anchor=tk.NW)
        self.keyword=tk.StringVar()        
        tk.Entry(lf1,width=50,textvariable=self.keyword).pack(anchor=tk.NW,expand='true',fill='x')

        # lf1_2=tk.LabelFrame(lf1,text='文件夾路徑:')
        lf1_2=tk.Frame(lf1)
        lf1_2.pack(anchor=tk.NW,ipadx=60,ipady=10,padx=5)   
        # tk.Label(lf1_2,text='文件夾路徑:').pack(side=tk.LEFT)
        tk.Label(lf1_2,text='文件夾路徑:').pack(anchor=tk.NW)        
        self.file1=tk.StringVar()        
        tk.Entry(lf1_2,width=40,textvariable=self.file1).pack(anchor=tk.NW)
        vButton = tk.Button(lf1_2, text='...', width=3,command=self.getfile)
        # vButton.pack(side=tk.LEFT)
        vButton.pack(anchor=tk.NW)
        
        tk.Label(lf1,text='所需圖片數量:').pack(anchor=tk.NW)        
        self.pic_number=tk.StringVar()  
        self.pic_number.set(10)      
        tk.Entry(lf1,width=10,textvariable=self.pic_number).pack(anchor=tk.NW)

        
        vButton = tk.Button(lf1, text='下載1', width=8,command=self.Call_baidu_Downpic02)
        vButton.pack(side=tk.LEFT)

    def Call_baidu_Downpic02(self):
        # print(self.keyword.get())
        # print(self.file1.get())
        # print(self.pic_number.get())
        if self.keyword.get()=='' or self.file1.get()=='' or self.pic_number.get()=='':
            # print('sssss')
            tkinter.messagebox.showerror(title='操作失敗', message='有參數爲空,請先檢查')
        else:
            try:
                pic_number1=int(self.pic_number.get())
                call_DownPic02_main(self.keyword.get(),self.file1.get(),pic_number1)
                tkinter.messagebox.showinfo(title='操作完成', message='操作完成')
            except:
                import sys
                tuple=sys.exc_info()
                errmsg='導入圖片失敗'+'錯誤爲:'+str(tuple[1])
                tkinter.messagebox.showerror(title='操作失敗', message=errmsg)

    def getfile(self):
        xx = tk.filedialog.askdirectory()
        self.file1.set(xx)

    # 設立函數,來取得當前時間,作爲文件名的一部分,以免文件名重複
    def get_sysdate2(self):
        now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
        # print(now)
        return now

    def setCenter(self,root, w, h):
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        x = int((ws / 2) - (w / 2))
        y = int((hs / 2) - (h / 2))
        root.geometry('{}x{}+{}+{}'.format(w, h, x, y))

    #類的運行主體
    def __init__(self):
        # self.root = tk.Tk()   #本界面單獨運行時,需要用到本行語句
        self.root = tk.Toplevel()
        self.root.title(string='Baidu 圖片下載 管理')
        self.setCenter(self.root, 700, 300)
        self.setupUI()
        self.root.mainloop()

if __name__=='__main__':
    Tl_baidu_DownPic02_screen()

主程式如下:


import json
import itertools
import urllib
import requests
import os
import re
import sys
import time

# 設立函數,來取得當前時間,作爲文件名的一部分,以免文件名重複


def get_sysdate():
    now = time.strftime("%m%d-%H%M%S", time.localtime(time.time()))
    print(now)
    return now


str_table = {
    '_z2C$q': ':',
    '_z&e3B': '.',
    'AzdH3F': '/'
}

char_table = {
    'w': 'a',
    'k': 'b',
    'v': 'c',
    '1': 'd',
    'j': 'e',
    'u': 'f',
    '2': 'g',
    'i': 'h',
    't': 'i',
    '3': 'j',
    'h': 'k',
    's': 'l',
    '4': 'm',
    'g': 'n',
    '5': 'o',
    'r': 'p',
    'q': 'q',
    '6': 'r',
    'f': 's',
    'p': 't',
    '7': 'u',
    'e': 'v',
    'o': 'w',
    '8': '1',
    'd': '2',
    'n': '3',
    '9': '4',
    'c': '5',
    'm': '6',
    '0': '7',
    'b': '8',
    'l': '9',
    'a': '0'
}

# str 的translate方法需要用單個字符的十進制unicode編碼作爲key
# value 中的數字會被當成十進制unicode編碼轉換成字符
# 也可以直接用字符串作爲value
char_table = {ord(key): ord(value) for key, value in char_table.items()}

# 解碼圖片URL


def decode(url):
    # 先替換字符串
    for key, value in str_table.items():
        url = url.replace(key, value)
    # 再替換剩下的字符
    return url.translate(char_table)

# 生成網址列表


def buildUrls(word):
    word = urllib.parse.quote(word)  # 屏蔽特殊的字符、比如如果url裏面的空格!url裏面是不允許出現空格的
    url = r"http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&fp=result&queryWord={word}&cl=2&lm=-1&ie=utf-8&oe=utf-8&st=-1&ic=0&word={word}&face=0&istype=2nc=1&pn={pn}&rn=60"
    urls = (url.format(word=word, pn=x)
            for x in itertools.count(start=0, step=60))  # itertools是python內置的模塊,count是生成無界限序列,從0開始,步長爲60,無限循環
    return urls


# 解析JSON獲取圖片URL,
# 一個圖片對應許多鏈接,經測試圖片鏈接在 objURL 這個標籤內。用正則找出
# 括號表示分組,將括號的內容捕獲到分組當中
#  這個括號也就可以匹配網頁中圖片的url了
re_url = re.compile(r'"objURL":"(.*?)"')  # 根據包含正則表達式的字符串創建模式對象


def resolveImgUrl(html):
    imgUrls = [decode(x) for x in re_url.findall(html)]
    # print(imgUrls)
    return imgUrls
    # for x in re_url.findall(html):
    #     print('aaa:')
    #     print(x)
    #     imgUrls=decode(x)
    #     print('bbb:')
    #     print(imgUrls)
    # return imgUrls


def downImg(imgUrl, dirpath, imgName):
    filename = os.path.join(dirpath, imgName)
    try:
        res = requests.get(imgUrl, timeout=15)
        if str(res.status_code)[0] == "4":
            #    print(str(res.status_code), ":", imgUrl)
            return False
    except Exception as e:
        print("拋出異常:", imgUrl)
        print(e)
        return False
    with open(filename, "wb") as f:
        f.write(res.content)
    return True


def mkDir(dirName):
    dirpath = os.path.join(sys.path[0], dirName)
    if not os.path.exists(dirpath):
        os.mkdir(dirpath)
    return dirpath


def Tl_baidu_DownPic02(keyword, download_dir, pic_number):
    word = keyword

    dir2 = os.path.join(download_dir, word, get_sysdate())
    print(dir2)
    if not os.path.exists(dir2):
        os.makedirs(dir2)

#    dirpath = mkDir("results")
    dirpath = dir2

    urls = buildUrls(word)
    index = 0
    for url in urls:
        #    print("正在請求:", url)
        html = requests.get(url, timeout=10).content.decode(
            'utf-8')  # 變量html 保留了一份Json文件,其中 objURL 是 圖片對應在網址
        #    print("正在請求:", html)
        imgUrls = resolveImgUrl(html)
        if len(imgUrls) == 0 or index >= pic_number:  # 沒有圖片則結束
            break
        for url in imgUrls:
            if downImg(url, dirpath, str(index) + ".jpg"):
                index += 1
                print("已下載 %s 張" % index)
                if index >= pic_number:
                    break


if __name__ == '__main__':
    #    print("歡迎使用百度圖片下載腳本!\n目前僅支持單個關鍵詞。")
    #    print("下載結果保存在腳本目錄下的results文件夾中。")
    #    print("=" * 50)
    #    word = input("請輸入你要下載的圖片關鍵詞:\n")
    Tl_baidu_DownPic02('Raspberry', 'e://', 50)


def call_DownPic02_main(keyword, download_dir, pic_number):
    #    print("歡迎使用百度圖片下載腳本!\n目前僅支持單個關鍵詞。")
    #    print("下載結果保存在腳本目錄下的results文件夾中。")
    #    print("=" * 50)
    #    word = input("請輸入你要下載的圖片關鍵詞:\n")
    # Tl_baidu_DownPic02('Raspberry',50)
    Tl_baidu_DownPic02(keyword, download_dir, pic_number)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章