日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python爬虫网络数据包_Python爬虫之多线程图虫网数据爬取(十六)

發(fā)布時(shí)間:2025/3/13 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫网络数据包_Python爬虫之多线程图虫网数据爬取(十六) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python爬蟲之多線程圖蟲網(wǎng)數(shù)據(jù)爬取(十六)

發(fā)布時(shí)間:2019-05-14 10:11,

瀏覽次數(shù):289

, 標(biāo)簽:

Python

原創(chuàng)不易,轉(zhuǎn)載前請(qǐng)注明博主的鏈接地址:Blessy_Zhu

https://blog.csdn.net/weixin_42555080

本次代碼的環(huán)境:

運(yùn)行平臺(tái): Windows

Python版本: Python3.x

IDE: PyCharm

<>一、 前言

今天要爬取的網(wǎng)站是圖蟲網(wǎng) (網(wǎng)址:https://tuchong.com/explore/

),這是一個(gè)個(gè)人非常喜歡的圖片分享展示和交流的平臺(tái)。上面的作品質(zhì)量非常高,對(duì)于我這個(gè)攝影小白來(lái)說(shuō)是一個(gè)非常不錯(cuò)的學(xué)習(xí)和欣賞大家作品的優(yōu)質(zhì)平臺(tái)。沒(méi)有做廣告哦,只是純屬個(gè)人喜歡的推薦。本篇博文的主要內(nèi)容是利用

隊(duì)列數(shù)據(jù)存取以及多線程爬蟲的方法爬取圖蟲網(wǎng)上面的圖片數(shù)據(jù)。好啦,ENOUGH TALK,LET‘S START IT!!!!!!!!!!!

<>二、思路過(guò)程

對(duì)于上面圖片上的題材,想必廣大宅男們肯定和我一樣,會(huì)毫不猶豫的選擇——風(fēng)光。別問(wèn)為什么,作為宅男,天天宅在家里,哪有時(shí)間旅游去欣賞自然風(fēng)光。所以還不如下載一下圖片聊以慰藉。

好,繼續(xù)繼續(xù)!!!!!!

首先點(diǎn)開(kāi)風(fēng)光圖,一直下來(lái),可以看到一個(gè)點(diǎn)擊加載更多的按鈕,這說(shuō)明它的數(shù)據(jù)傳輸方式是AJAX。

接下里摁下F12,找到Network,點(diǎn)擊XHR,然后刷新,接著點(diǎn)擊加載更多發(fā)現(xiàn)通過(guò)AJAX傳過(guò)來(lái)的數(shù)據(jù)包就會(huì)又出現(xiàn)一個(gè)。可以看到這些發(fā)過(guò)來(lái)的數(shù)據(jù)包很有規(guī)律,它們的命名都是

posts?page={ }&count=20&order=weekly也就是只有page屬性的值在改變。

接下來(lái)看一下它的請(qǐng)求URL(Request URL):

https://tuchong.com/rest/tags/風(fēng)光/posts?page={}&count=20&order=weekly

,也是只有page屬性改變。這下子就太好了!!!

然后訪問(wèn)Request URL,wonderful!!!!!!!!!!!拿到數(shù)據(jù)了,而且這個(gè)數(shù)據(jù)還是字典型的。那就更Easy了!!!

繼續(xù)探究,點(diǎn)開(kāi)preview,可以看到,這些AJAX數(shù)據(jù)。

隨便點(diǎn)開(kāi)一個(gè),看看它里面的內(nèi)容,這里面的內(nèi)容幾乎是我們可見(jiàn)即可爬的全部數(shù)據(jù),”但是如水三千,只取一瓢飲“,既然是只下載圖片,那么就只看一個(gè)屬性就可以:cover_image_src:

“https://photo.tuchong.com/397845/g/488047063.webp

”,可以看到他的值除了兩部分?jǐn)?shù)字,其他都是固定的,這樣只需要搞懂那兩部分?jǐn)?shù)字是干什么的就可以了。通過(guò)觀察可以看到,前一部分?jǐn)?shù)字實(shí)際上就是屬性author_id的值,后一部分實(shí)際上就是屬性img_id的值,而這兩個(gè)值,通過(guò)字典的方式就可以獲取,這樣就可以拼接成一個(gè)完整的圖片下載地址了:

通過(guò)上面的過(guò)程,可以準(zhǔn)確的找到一個(gè)完整數(shù)據(jù)包的訪問(wèn)地址,每個(gè)完整數(shù)據(jù)包包括20個(gè)圖片信息。然后通過(guò)訪問(wèn)數(shù)據(jù)包可以將圖片的下載地址進(jìn)行拼接,從而最后實(shí)現(xiàn)圖片的下載。

思路已經(jīng)清晰啦,接下來(lái)就開(kāi)始爬取代碼的編寫吧!!!!

<>三、代碼及結(jié)果分析展示

<>3.1 queue相關(guān)知識(shí)

本次使用python中的queue,也就是隊(duì)列來(lái)模擬數(shù)據(jù)的存取過(guò)程。

首先對(duì)于基本爬蟲初期,可以簡(jiǎn)單的使用到queue的知識(shí)可以如下所示:

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() 6. from queue import

Queue,這個(gè)數(shù)據(jù)包在Python3中是內(nèi)置了,不需要安裝

<>3.2 多線程框架

首先先實(shí)現(xiàn)多線的框架:

import threading for queue import Queue 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)************') def main(): # 聲明一個(gè)隊(duì)列,使用循環(huán)在里面存入

100個(gè)頁(yè)碼 page_queue = Queue(100) for i in range(1,101): page_queue.put(i) # 采集結(jié)果(

等待下載的圖片地址) data_queue = Queue() # 記錄線程的列表 thread_crawl = [] # 每次開(kāi)啟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():

passif __name__ == '__main__': main()

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

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

CRAWL_EXIT = False

CRAWL_EXIT = False class ThreadCrawl(threading.Thread): def __init__(self,

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

ThreadCrawl, self).__init__() self.threadName = thread_name self.page_queue =

page_queue defrun(self): print(self.threadName + ' 啟動(dòng)************') while not

CRAWL_EXIT: try: #global tag, url, img_format # 把全局的值拿過(guò)來(lái) headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,

like Gecko) Chrome/63.0.3239.132 Safari/537.36', } # 隊(duì)列為空 產(chǎn)生異常 page = self.

page_queue.get(block=False) # 從里面獲取值 spider_url =

'https://tuchong.com/rest/tags/%E8%87%AA%E7%84%B6/posts?page={}&count=20&order=weekly'

.format(page) 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: user_id = img["user_id"] img_id = img[

"img_id"] img_url = 'https://photo.tuchong.com/{}/f/{}.jpg'.format(user_id,

img_id) #self.data_queue.put(img_url) # 捕獲到圖片鏈接,之后,存入一個(gè)新的隊(duì)列里面,等待下一步的操作 title =

'download/' + str(img_id) response = requests.get(img_url) # 保存圖片名字有問(wèn)題,不知道會(huì)不會(huì)重復(fù)

withopen(title + '.jpg', 'wb') as f: f.write(response.content) time.sleep(3)

break except Exception as e: print(e) if timeout <= 0: print('time out!')

然后在main函數(shù)中添加如下代碼:

...... while not page_queue.empty(): pass # 如果page_queue為空,采集線程退出循環(huán) global

CRAWL_EXIT CRAWL_EXIT= True

結(jié)果如下:

<>四、總結(jié)

這篇文章是圖蟲網(wǎng)圖片數(shù)據(jù)的爬取,用到了隊(duì)列的思想存取數(shù)據(jù),同時(shí)采用多線程提高速度。這篇文章就到這里了,歡迎大佬們多批評(píng)指正,也歡迎大家積極評(píng)論多多交流。

<>附完整代碼:

import threading from queue import Queue import requests import os import time

CRAWL_EXIT= False class ThreadCrawl(threading.Thread): def __init__(self,

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

ThreadCrawl, self).__init__() self.threadName = thread_name self.page_queue =

page_queue defrun(self): print(self.threadName + ' 啟動(dòng)************') while not

CRAWL_EXIT: try: #global tag, url, img_format # 把全局的值拿過(guò)來(lái) headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,

like Gecko) Chrome/63.0.3239.132 Safari/537.36', } # 隊(duì)列為空 產(chǎn)生異常 page = self.

page_queue.get(block=False) # 從里面獲取值 spider_url =

'https://tuchong.com/rest/tags/%E8%87%AA%E7%84%B6/posts?page={}&count=20&order=weekly'

.format(page) 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: user_id = img["user_id"] img_id = img[

"img_id"] img_url = 'https://photo.tuchong.com/{}/f/{}.jpg'.format(user_id,

img_id) #self.data_queue.put(img_url) # 捕獲到圖片鏈接,之后,存入一個(gè)新的隊(duì)列里面,等待下一步的操作 title =

'download/' + str(img_id) response = requests.get(img_url) # 保存圖片名字有問(wèn)題,不知道會(huì)不會(huì)重復(fù)

withopen(title + '.jpg', 'wb') as f: f.write(response.content) time.sleep(3)

break except Exception as e: print(e) if timeout <= 0: print('time out!') def

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

page_queue.put(i) # 采集結(jié)果(等待下載的圖片地址) #data_queue = Queue() # 記錄線程的列表 thread_crawl

= [] # 每次開(kāi)啟4個(gè)線程 craw_list = ['采集線程1號(hào)','采集線程2號(hào)','采集線程3號(hào)','采集線程4號(hào)'] if not os.path

.exists('download'): os.mkdir('download') for thread_name in craw_list: c_thread

= ThreadCrawl(thread_name, page_queue) c_thread.start() thread_crawl.append(

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

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

'__main__': main()

總結(jié)

以上是生活随笔為你收集整理的python爬虫网络数据包_Python爬虫之多线程图虫网数据爬取(十六)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。