Python3 根據關鍵字爬取百度圖片


介紹

  1. 一個可用好用的百度圖片爬取腳本,唯一的不足就是這是單線程的
  2. 運行環境 Python3.6.0
  3. 寫該腳本的原因:獲取圖片
  4. 創作過程有參考

源碼

# coding:utf-8
import requests
import os
import re
# import json
import itertools
import urllib
import sys

# 百度圖片URL解碼
# http://blog.csdn.net/hbuxiaoshe/article/details/44780653
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'
}
char_table = {ord(key): ord(value) for key, value in char_table.items()}

# 解碼
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 = 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))
    return urls


re_url = re.compile(r'"objURL":"(.*?)"')

# 獲取imgURL
def resolveImgUrl(html):
    imgUrls = [decode(x) for x in re_url.findall(html)]
    return imgUrls

# 下載圖片
def downImgs(imgUrl, dirpath, imgName, imgType):
    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 + '.' + imgType, '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


if __name__ == '__main__':
    print("歡迎使用百度圖片下載爬蟲\n 多個關鍵字請用空格進行分割\n")
    # print("下載結果保存在腳本目錄下的img文件夾中。")
    choosePath = input('請輸入你想保存的路徑方式\n 1. 默認路徑 path = IMGS/ \n 2. 相對路徑 path_input/path_input/ \n 3. 絕對路徑,比如 D:/IMG/\n')
    if int(choosePath) == 3:
        dirpath = input('請輸入您要保存圖片的路徑\n')
    elif int(choosePath) == 2:
        path = input('請輸入您要保存圖片的路徑\n')
        dirpath = mkDir(path)
    else:
        path = 'IMGS'
        dirpath = mkDir(path)

    print("= = " * 25)
    word = input("請輸入你要下載的圖片關鍵詞:\n")
    print("= = " * 25)

    chooseImgType = input('請選擇你要保存的圖片格式\n 0. default: jpg \n 1. jpg\n 2. png\n 3. gif\n 4. 自定義\n')
    chooseImgType = int(chooseImgType)
    if chooseImgType == 4:
        imgType = input('請輸入自定義圖片類型\n')
    elif chooseImgType == 1:
        imgType = 'jpg'
    elif chooseImgType == 2:
        imgType = 'png'
    elif chooseImgType == 3:
        imgType = 'gif'
    else:
        imgType = 'jpg'
    print("= = " * 25)

    strtag = input("請輸入您要下載圖片名字,最后格式為 number+' ' +name.%s\n" % imgType)

    print("= = " * 25)
    numIMGS = input('請輸入您要下載圖片的數量\n')
    numIMGS = int(numIMGS)

    urls = buildUrls(word)
    index = 0
    print("= = " * 25)
    for url in urls:
        print("正在請求:", url)
        html = requests.get(url, timeout=10).content.decode('utf-8')
        imgUrls = resolveImgUrl(html)
        # print(imgUrls)
        if len(imgUrls) == 0:  # 沒有圖片則結束
            break
        for url in imgUrls:
            if downImgs(url, dirpath, str(index + 1) + ' ' + strtag, imgType):
                index += 1
                print("已下載 %s 張" % index)
                # 雙 break 跳出下載循環
            if index == numIMGS:
                break
        if index == numIMGS:
            print('您一共下載了 %s 張圖片' % index)
            print('程序正在終止')
            break

運行演示

運行演示一

運行演示二

爬取的圖片

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM