圖蟲網(wǎng)-寫在前面

經(jīng)歷了一頓噼里啪啦的操作之后,終于我把博客寫到了第10篇,后面,慢慢的會(huì)涉及到更多的爬蟲模塊,有人問 scrapy 啥時(shí)候開始用,這個(gè)我預(yù)計(jì)要在30篇以后了吧,后面的套路依舊慢節(jié)奏的,所以莫著急了,100篇呢,預(yù)計(jì)4~5個(gè)月寫完,常見的反反爬后面也會(huì)寫的,還有fuck login類的內(nèi)容。

圖蟲網(wǎng)-爬取圖蟲網(wǎng)

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

起始頁面

https://tuchong.com/explore/
這個(gè)頁面中有很多的標(biāo)簽,每個(gè)標(biāo)簽下面都有很多圖片,為了和諧,我選擇了一個(gè)非常好的標(biāo)簽 花卉 你可以選擇其他的,甚至,你可以把所有的都爬取下來。

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

            
          

我們這次也玩點(diǎn)以前沒寫過的,使用python中的queue,也就是隊(duì)列

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

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

2\. 包中的常用方法:

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

3. 創(chuàng)建一個(gè)“隊(duì)列”對(duì)象
    import queue
    myqueue = queue.Queue(maxsize = 10)

4. 將一個(gè)值放入隊(duì)列中
    myqueue.put(10)

5. 將一個(gè)值從隊(duì)列中取出
    myqueue.get()

            
          

開始編碼

首先我們先實(shí)現(xiàn)主要方法的框架,我依舊是把一些核心的點(diǎn),都寫在注釋上面

            
              def main():
    # 聲明一個(gè)隊(duì)列,使用循環(huán)在里面存入100個(gè)頁碼
    page_queue  = Queue(100)
    for i in range(1,101):
        page_queue.put(i)

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

    # 記錄線程的列表
    thread_crawl = []
    # 每次開啟4個(gè)線程
    craw_list = ['采集線程1號(hào)','采集線程2號(hào)','采集線程3號(hào)','采集線程4號(hào)']
    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隊(duì)列為空,也就是等待之前的操作執(zhí)行完畢
    while not page_queue.empty():
        pass

if __name__ == '__main__':
    main()
Python資源分享qun 784758214 ,內(nèi)有安裝包,PDF,學(xué)習(xí)視頻,這里是Python學(xué)習(xí)者的聚集地,零基礎(chǔ),進(jìn)階,都?xì)g迎
            
          

代碼運(yùn)行之后,成功啟動(dòng)了4個(gè)線程,然后等待線程結(jié)束,這個(gè)地方注意,你需要把 ThreadCrawl 類補(bǔ)充完整

            
              class ThreadCrawl(threading.Thread):

    def __init__(self, thread_name, page_queue, data_queue):
        # threading.Thread.__init__(self)
        # 調(diào)用父類初始化方法
        super(ThreadCrawl, self).__init__()
        self.threadName = thread_name
        self.page_queue = page_queue
        self.data_queue = data_queue

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

            
          

運(yùn)行結(jié)果

線程已經(jīng)開啟,在run方法中,補(bǔ)充爬取數(shù)據(jù)的代碼就好了,這個(gè)地方引入一個(gè)全局變量,用來標(biāo)識(shí)爬取狀態(tài)
CRAWL_EXIT = False

先在 main 方法中加入如下代碼

            
              CRAWL_EXIT = False  # 這個(gè)變量聲明在這個(gè)位置
class ThreadCrawl(threading.Thread):

    def __init__(self, thread_name, page_queue, data_queue):
        # threading.Thread.__init__(self)
        # 調(diào)用父類初始化方法
        super(ThreadCrawl, self).__init__()
        self.threadName = thread_name
        self.page_queue = page_queue
        self.data_queue = data_queue

    def run(self):
        print(self.threadName + ' 啟動(dòng)************')
        while not CRAWL_EXIT:
            try:
                global tag, url, headers,img_format  # 把全局的值拿過來
                # 隊(duì)列為空 產(chǎn)生異常
                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)  # 捕獲到圖片鏈接,之后,存入一個(gè)新的隊(duì)列里面,等待下一步的操作

                    break

                except Exception as e:
                    print(e)

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

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

    # 如果page_queue為空,采集線程退出循環(huán)
    global CRAWL_EXIT
    CRAWL_EXIT = True

    # 測試一下隊(duì)列里面是否有值
    print(data_queue)

            
          

經(jīng)過測試,data_queue 里面有數(shù)據(jù)啦??!,哈哈,下面在使用相同的操作,去下載圖片就好嘍

完善 main 方法

            
              def main():
    # 代碼在上面

    for thread in thread_crawl:
        thread.join()
        print("抓取線程結(jié)束")

    thread_image = []
    image_list = ['下載線程1號(hào)', '下載線程2號(hào)', '下載線程3號(hào)', '下載線程4號(hào)']
    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("下載線程結(jié)束")

            
          

還是補(bǔ)充一個(gè) ThreadDown 類,這個(gè)類就是用來下載圖片的。

            
              
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 + ' 啟動(dòng)************')
        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   # 獲取二進(jìn)制流

        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
Python資源分享qun 784758214 ,內(nèi)有安裝包,PDF,學(xué)習(xí)視頻,這里是Python學(xué)習(xí)者的聚集地,零基礎(chǔ),進(jìn)階,都?xì)g迎
            
          

運(yùn)行之后,等待圖片下載就可以啦~~

關(guān)鍵注釋已經(jīng)添加到代碼里面了,收圖吧 (????),這次代碼回頭在上傳到 github 上 因?yàn)楸容^簡單

當(dāng)你把上面的花卉修改成比如 xx 啥的 ,就是 天外飛仙