Python批量抓取站酷ZCOOL作品圖片並歸檔

摩卡的大叔發表於2017-12-19

前言

前幾天,由於個人有需求,所以就要對站酷網一些類別下的作品的圖片進行批量抓取,首先是採用的是NodeJs來寫的,但是在執行的途中遇到很多的問題,所以後來就換成了Python,同時使用了多執行緒,使得圖片下載時達到了寬頻的峰值,同樣也保證了其質量。

正文

我本次採用的是request和BeautifulSoup組合來進行抓取的,首先我們需要分析站酷的DOM結構:

Python批量抓取站酷ZCOOL作品圖片並歸檔

由上我們可以看出,其主要內容包含在class為work-list-box的這個div內,並且每個作品又是單獨包含在class為card-box這個div內的,所以我們需要獲取到頁面所有的作品元素集合,我封裝成了一個函式:

def startRequest(url):
    print("【提示】正在抓取 - %s " % url)
    res = requests.get(url)
    if res.status_code == 200:
        res_html = res.content.decode()
        doc = BeautifulSoup(res_html)
        work_box = doc.find('div', class_={'work-list-box'})
        card_box_list = work_box.find_all('div', class_={'card-box'}) # 此處為所有的作品元素集合
    else:
        print("【文件獲取失敗】【狀態為%s】 - %s," % (url, res.status_code))
複製程式碼

接下來分析每個模組元素的結構,通過檢視DOM元素得知每個card-box下的class為title-content的這個a標籤包含了其作品的連結地址以及作品標題,所以我們就可以由此來獲取:

title_content = item.find("a", class_={'title-content'})
avatar = item.find('span', class_={'user-avatar'})
複製程式碼

但是在作品集合元素內,巢狀著推廣或廣告,但是推廣和廣告是沒有頭像avatar元素的,所以我們只需要這樣檢測頭像是否為空就可以過濾掉廣告元素,其後獲取到作者,URL連結以及標題:

def getContent(item):
    title_content = item.find("a", class_={'title-content'})
    avatar = item.find('span', class_={'user-avatar'})
    if title_content is not None and avatar is not None:
        title = title_content.text
        author = avatar.find("a")["title"]
        href = title_content['href']
    else:
        return
複製程式碼

接下來,我們需要訪問對應的URL,並獲取到其中的URL地址:

Python批量抓取站酷ZCOOL作品圖片並歸檔

通過檢視DOM元素結構可以看出,其文章主要內容區域在class為work-show-box的div下,然後每個圖片/視訊/文字區域都是放在class為reveal-work-wrap的div內,所以獲取到所有的內容區域集合,然後檢視是否有img標籤,如果有的話就說明存在圖片元素,則是我們需要的內容,並且獲取到其src存放至url的集合中去:

def getDocImgLinks(html):
    doc = BeautifulSoup(html)
    work_box = doc.find("div", class_={'work-show-box'})
    revs = work_box.find_all("div", class_={'reveal-work-wrap'})
    img_list = []
    for item in revs:
        img = item.find("img")
        if img is not None:
            img_url = img["src"]
            img_list.append(img_url)
        else:
            print("【提示】:沒有圖片")
            continue
    return img_list
複製程式碼

要注意的一點就是,其中有些圖片如上圖中,會存在@這個表示,就好比http://img.zcool.cn/community/0170165a372344a80121db8001781d.jpg@1280w_1l_2o_100sh.jpg,這個是將原圖片進行了裁剪的縮圖,我們只需要將@以及後面的內容去掉就可以得到原圖,最後為:http://img.zcool.cn/community/0170165a372344a80121db8001781d.jpg

最後,我們需要將獲取的URL圖片進行儲存,儲存的資料夾就以【作者名】-【作品標題】為標準,然後圖片就以UUID來隨機命名,同時我們需要對一些特殊字元進行過濾轉換,以防建立資料夾或檔案失敗:

def nameEncode(file_name):
    file_stop_str = ['\\', '/', '*', '?', ':', '"', '<', '>', '|']
    for item2 in file_stop_str:
        file_name = file_name.replace(item2, '-')
    return file_name
複製程式碼

所以,最後的完整原始碼如下:

import sys
from bs4 import BeautifulSoup
import requests
import os
import uuid
import threading


def startRequest(url):
    print("【提示】正在抓取 - %s " % url)
    res = requests.get(url)
    if res.status_code == 200:
        res_html = res.content.decode()
        doc = BeautifulSoup(res_html)
        work_box = doc.find('div', class_={'work-list-box'})
        card_box_list = work_box.find_all('div', class_={'card-box'})
        for item in card_box_list:
            getContent(item)
    else:
        print("【文件獲取失敗】【狀態為%s】 - %s," % (url, res.status_code))


def getContent(item):
    title_content = item.find("a", class_={'title-content'})
    avatar = item.find('span', class_={'user-avatar'})
    if title_content is not None and avatar is not None:
        title = title_content.text
        author = avatar.find("a")["title"]
        href = title_content['href']
        # print("%s - 【%s】- %s" % (title, author, href))
        res = requests.get(href)
        if res.status_code == 200:
            # 獲取所有的圖片連結
            img_list = getDocImgLinks(res.content.decode())
            path_str = "【%s】-【%s】" % (author, title)
            path_str_mk = pathBase('./data/'+nameEncode(path_str))
            if path_str_mk is None:
                return
            else:
                for img_item in img_list:
                    downloadImg(img_item, path_str_mk)

        else:
            print("【文件獲取失敗】【狀態為%s】 - %s," % (href, res.status_code))
    else:
        return


def getDocImgLinks(html):
    doc = BeautifulSoup(html)
    work_box = doc.find("div", class_={'work-show-box'})
    revs = work_box.find_all("div", class_={'reveal-work-wrap'})
    img_list = []
    for item in revs:
        img = item.find("img")
        if img is not None:
            img_url = img["src"]
            img_list.append(img_url)
        else:
            print("【提示】:沒有圖片")
            continue
    return img_list


def pathBase(file_path):
    file_name_s = file_path.split("/")
    file_name = file_name_s[len(file_name_s) - 1]
    file_name_s[len(file_name_s) - 1] = file_name
    path = "/".join(file_name_s)
    if not os.path.exists(path):
        os.mkdir(path)
    return path


def nameEncode(file_name):
    file_stop_str = ['\\', '/', '*', '?', ':', '"', '<', '>', '|']
    for item2 in file_stop_str:
        file_name = file_name.replace(item2, '-')
    return file_name


def downloadImg(url, path):
    z_url = url.split("@")[0]
    hz = url.split(".")
    z_hz = hz[len(hz) - 1]
    res = requests.get(z_url)
    if res.status_code == 200:
        img_down_path = path + "/" + str(uuid.uuid1()) + "." + z_hz
        f = open(img_down_path, 'wb')
        f.write(res.content)
        f.close()
        print("【下載成功】 -  %s" % img_down_path)
    else:
        print("【IMG下載失敗】【狀態為%s】 - %s," % (z_url, res.status_code))


if __name__ == '__main__':
    threads = []

    for i in range(1, 22):
        url = 'http://www.zcool.com.cn/search/content?type=3&field=8&other=0&sort=5&word=APP%E8%AE%BE%E8%AE%A1' \
              '&recommend=0&requestId=requestId_1513228221822&p='+(str(i))+'#tab_anchor '
        threads.append(threading.Thread(target=startRequest, args={url}))

    for item in threads:
        item.start()
複製程式碼

後記

說說最後的效果吧,通過幾十分鐘的抓取,峰值為11MB的下載速度,成功抓取了站酷網站的2500+的作品,總大小為30GB左右。如果上述程式碼中有任何不清楚的地方,您可以在下方進行留言,我會及時回答您的疑惑。


原文連結:www.licoy.cn/3019.html


相關文章