1. 程式人生 > >Python爬蟲入門教程 10-100 圖蟲網多執行緒爬取

Python爬蟲入門教程 10-100 圖蟲網多執行緒爬取

寫在前面

經歷了一頓噼裡啪啦的操作之後,終於我把部落格寫到了第10篇,後面,慢慢的會涉及到更多的爬蟲模組,有人問scrapy 啥時候開始用,這個我預計要在30篇以後了吧,後面的套路依舊慢節奏的,所以莫著急了,100篇呢,預計4~5個月寫完,常見的反反爬後面也會寫的,還有fuck login類的內容。

爬取圖蟲網

為什麼要爬取這個網站,不知道哎~ 莫名奇妙的收到了,感覺圖片質量不錯,不是那些妖豔賤貨 可以比的,所以就開始爬了,搜了一下網上有人也在爬,但是基本都是py2,py3的還沒有人寫,所以順手寫一篇吧。

起始頁面

https://tuchong.com/explore/
這個頁面中有很多的標籤,每個標籤下面都有很多圖片,為了和諧,我選擇了一個非常好的標籤花卉

你可以選擇其他的,甚至,你可以把所有的都爬取下來。

https://tuchong.com/tags/%E8%8A%B1%E5%8D%89/  # 花卉編碼成了  %E8%8A%B1%E5%8D%89  這個無所謂

我們這次也玩點以前沒寫過的,使用python中的queue,也就是佇列

下面是我從別人那順來的一些解釋,基本爬蟲初期也就用到這麼多

1. 初始化: class Queue.Queue(maxsize) FIFO 先進先出

2. 包中的常用方法:

    - queue.qsize() 返回佇列的大小
    - queue.empty() 如果佇列為空,返回True,反之False
    - queue.full() 如果佇列滿了,返回True,反之False
    - queue.full 與 maxsize 大小對應
    - queue.get([block[, timeout]])獲取佇列,timeout等待時間

3. 建立一個“佇列”物件
    import queue
    myqueue = queue.Queue(maxsize = 10)

4. 將一個值放入佇列中
    myqueue.put(10)

5. 將一個值從佇列中取出
    myqueue.get()

開始編碼

首先我們先實現主要方法的框架,我依舊是把一些核心的點,都寫在註釋上面

def main():
    # 宣告一個佇列,使用迴圈在裡面存入100個頁碼
    page_queue  = Queue(100)
    for i in range(1,101):
        page_queue.put(i)


    # 採集結果(等待下載的圖片地址)
    data_queue = Queue()

    # 記錄執行緒的列表
    thread_crawl = []
    # 每次開啟4個執行緒
    craw_list = ['採集執行緒1號','採集執行緒2號','採集執行緒3號','採集執行緒4號']
    for thread_name in craw_list:
        c_thread = ThreadCrawl(thread_name, page_queue, data_queue)
        c_thread.start()
        thread_crawl.append(c_thread)

    # 等待page_queue佇列為空,也就是等待之前的操作執行完畢
    while not page_queue.empty():
        pass

if __name__ == '__main__':
    main()

程式碼執行之後,成功啟動了4個執行緒,然後等待執行緒結束,這個地方注意,你需要把 ThreadCrawl 類補充完整

class ThreadCrawl(threading.Thread):

    def __init__(self, thread_name, page_queue, data_queue):
        # threading.Thread.__init__(self)
        # 呼叫父類初始化方法
        super(ThreadCrawl, self).__init__()
        self.threadName = thread_name
        self.page_queue = page_queue
        self.data_queue = data_queue

    def run(self):
        print(self.threadName + ' 啟動************')

執行結果
在這裡插入圖片描述

執行緒已經開啟,在run方法中,補充爬取資料的程式碼就好了,這個地方引入一個全域性變數,用來標識爬取狀態
CRAWL_EXIT = False

先在main方法中加入如下程式碼

CRAWL_EXIT = False  # 這個變數宣告在這個位置
class ThreadCrawl(threading.Thread):

    def __init__(self, thread_name, page_queue, data_queue):
        # threading.Thread.__init__(self)
        # 呼叫父類初始化方法
        super(ThreadCrawl, self).__init__()
        self.threadName = thread_name
        self.page_queue = page_queue
        self.data_queue = data_queue

    def run(self):
        print(self.threadName + ' 啟動************')
        while not CRAWL_EXIT:
            try:
                global tag, url, headers,img_format  # 把全域性的值拿過來
                # 佇列為空 產生異常
                page = self.page_queue.get(block=False)   # 從裡面獲取值
                spider_url = url_format.format(tag,page,100)   # 拼接要爬取的URL
                print(spider_url)
            except:
                break

            timeout = 4   # 合格地方是嘗試獲取3次,3次都失敗,就跳出
            while timeout > 0:
                timeout -= 1
                try:
                    with requests.Session() as s:
                        response = s.get(spider_url, headers=headers, timeout=3)
                        json_data = response.json()
                        if json_data is not None:
                            imgs = json_data["postList"]
                            for i in imgs:
                                imgs = i["images"]
                                for img in imgs:
                                    img = img_format.format(img["user_id"],img["img_id"])
                                    self.data_queue.put(img)  # 捕獲到圖片連結,之後,存入一個新的佇列裡面,等待下一步的操作

                    break

                except Exception as e:
                    print(e)


            if timeout <= 0:
                print('time out!')
def main():
    # 程式碼在上面

    # 等待page_queue佇列為空,也就是等待之前的操作執行完畢
    while not page_queue.empty():
        pass

    # 如果page_queue為空,採集執行緒退出迴圈
    global CRAWL_EXIT
    CRAWL_EXIT = True
    
    # 測試一下佇列裡面是否有值
    print(data_queue)

經過測試,data_queue 裡面有資料啦!!,哈哈,下面在使用相同的操作,去下載圖片就好嘍
在這裡插入圖片描述
完善main方法

def main():
    # 程式碼在上面

    for thread in thread_crawl:
        thread.join()
        print("抓取執行緒結束")

    thread_image = []
    image_list = ['下載執行緒1號', '下載執行緒2號', '下載執行緒3號', '下載執行緒4號']
    for thread_name in image_list:
        Ithread = ThreadDown(thread_name, data_queue)
        Ithread.start()
        thread_image.append(Ithread)



    while not data_queue.empty():
        pass

    global DOWN_EXIT
    DOWN_EXIT = True

    for thread in thread_image:
        thread.join()
        print("下載執行緒結束")

還是補充一個 ThreadDown 類,這個類就是用來下載圖片的。


class ThreadDown(threading.Thread):
    def __init__(self, thread_name, data_queue):
        super(ThreadDown, self).__init__()
        self.thread_name = thread_name
        self.data_queue = data_queue

    def run(self):
        print(self.thread_name + ' 啟動************')
        while not DOWN_EXIT:
            try:
                img_link = self.data_queue.get(block=False)
                self.write_image(img_link)
            except Exception as e:
                pass

    def write_image(self, url):

        with requests.Session() as s:
            response = s.get(url, timeout=3)
            img = response.content   # 獲取二進位制流

        try:
            file = open('image/' + str(time.time())+'.jpg', 'wb')
            file.write(img)
            file.close()
            print('image/' + str(time.time())+'.jpg 圖片下載完畢')

        except Exception as e:
            print(e)
            return

執行之後,等待圖片下載就可以啦~~

在這裡插入圖片描述
關鍵註釋已經新增到程式碼裡面了,收圖吧 (◕ᴗ◕✿),這次程式碼回頭在上傳到github上 因為比較簡單
在這裡插入圖片描述
當你把上面的花卉修改成比如xx啥的~,就是天外飛仙