1. 程式人生 > >新手入門大資料 Hadoop基礎與電商行為日誌分析

新手入門大資料 Hadoop基礎與電商行為日誌分析

爬取圖蟲網

為什麼要爬取這個網站,不知道哎~ 莫名奇妙的收到了,感覺圖片質量不錯,不是那些妖豔賤貨 可以比的,所以就開始爬了,搜了一下網上有人也在爬,但是基本都是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)