多線程爬蟲流程

1.多線程爬蟲流程分析

在這裏插入圖片描述

2.queue模塊

2.1Queue:先進先出隊列,類似火車站排隊

from queue import Queue
# Queue:先進先出隊列,類似火車站排隊

# 創建Queue對象
# maxsize 用於指定Queue隊列的容量,最多可以放多少元素,不指定則沒有限制
q = Queue(maxsize=3)
# 存儲元素
q.put(1)
q.put(2)
# q.put(3)

# qsize隊列中元素個數
print(q.qsize())  # 2
# 判斷隊列是否滿了
print(q.full())  # flase
# 取出數據
print(q.get())  # 1
print(q.get())  # 2

# 判斷隊列是否空了
print(q.empty())  # True

# 創建對象
q = Queue()
for i in range(4):
	q.put(i)
# 取出(先進先出)
while not q.empty():
	print(q.get())

輸出結果:0,1,2,3

2.2 LifoQueue: 後進先出隊列,類似於棧

from queue import LifoQueue
# LifoQueue: 後進先出隊列,類似於棧
# 創建對象
lq = LifoQueue()
for i in range(4):
	lq.put(i)
# 取出(先進先出)
while not lq.empty():
	print(lq.get())

輸出結果:3,2,1,0

2.3 priorityQueue:優先級隊列,在存儲數據時,會對元素進行排序

from queue import PriorityQueue
# priorityQueue:優先級隊列,在存儲數據時,會對元素進行排序

# 定義一個工作類
class Job(object):
	def __init__(self, level, work):
		self.level = level
		self.work = work
	def __lt__(self, other):
		#定義小於號方法
		return self.level < other.level
	def __str__(self):
		return '<level:{}, work:{}>'.format(self.level, self.work)
	

# 創建對象
pq = PriorityQueue()
# 存儲
pq.put(Job(3, '無關的工作'))
pq.put(Job(1, '重要的工作'))
pq.put(Job(2, '普通的工作'))

while not pq.empty():
	print(pq.get())

輸出結果:
<level:1, work:重要的工作>
<level:2, work:普通的工作>
<level:3, work:無關的工作>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章