爬虫——多线程糗事百科案例
生活随笔
收集整理的這篇文章主要介紹了
爬虫——多线程糗事百科案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Queue(隊列對象)
Queue是python中的標準庫,可以直接import Queue引用;隊列是線程間最常用的交換數據的形式
python下多線程的思考
對于資源,加鎖是個重要的環節。因為python原生的list,dict等,都是not thread safe的。而Queue,是線程安全的,因此在滿足使用條件下,建議使用隊列
初始化: class Queue.Queue(maxsize) FIFO 先進先出
包中的常用方法:
-
Queue.qsize() 返回隊列的大小
-
Queue.empty() 如果隊列為空,返回True,反之False
-
Queue.full() 如果隊列滿了,返回True,反之False
-
Queue.full 與 maxsize 大小對應
-
Queue.get([block[, timeout]])獲取隊列,timeout等待時間
創建一個“隊列”對象
- import Queue
- myqueue = Queue.Queue(maxsize = 10)
將一個值放入隊列中
- myqueue.put(10)
將一個值從隊列中取出
- myqueue.get()
多線程示意圖
多線程糗事百科案例代碼:
# coding=utf-8 import requests from lxml import etree from queue import Queue import threadingclass QiuBai:def __init__(self):self.temp_url = "https://www.qiushibaike.com/8hr/page/{}/"self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"}self.url_queue = Queue() #放url的隊列self.html_str_queue = Queue() #放響應的隊列self.content_list_queue = Queue() #放提取的數據的隊列def get_url_list(self): # 獲取url列表for i in range(1,14):self.url_queue.put(self.temp_url.format(i))def parse_url(self): # 發送請求,獲取html字符串while True:url = self.url_queue.get()print(url)r = requests.get(url, headers=self.headers)self.html_str_queue.put(r.content.decode())self.url_queue.task_done()def get_content_list(self):while True:html_str = self.html_str_queue.get()html = etree.HTML(html_str)div_list = html.xpath("//div[@id='content-left']/div")content_list = []for div in div_list:item = {}item["author_name"] = div.xpath(".//h2/text()")[0] if len(div.xpath(".//h2/text()")) > 0 else Noneitem["content"] = div.xpath(".//div[@class='content']/span/text()")item["img_list"] = div.xpath(".//div[@class='thumb']/a/img/@src")content_list.append(item)self.content_list_queue.put(content_list)self.html_str_queue.task_done()def save_content_list(self): # savewhile True:content_list = self.content_list_queue.get()for content in content_list:# print(content)passself.content_list_queue.task_done()def run(self): # 實現主要邏輯thread_list = []# 1.url_listt_url = threading.Thread(target=self.get_url_list)thread_list.append(t_url)# 2.發送請求,獲取數據for i in range(3):t_parse = threading.Thread(target=self.parse_url)thread_list.append(t_parse)# 3.提取數據for i in range(2):t_content_list = threading.Thread(target=self.get_content_list)thread_list.append(t_content_list)# 4.保存t_save = threading.Thread(target=self.save_content_list)thread_list.append(t_save)for t in thread_list:t.setDaemon(True) #設置為守護線程,守護線程:這個線程不重要,主線程結束,子線程結束t.start()for q in [self.url_queue,self.content_list_queue,self.html_str_queue]:q.join() #讓主線程等待著,知道隊列計數為0的時候,join失效print("主線程結束")if __name__ == '__main__':qiubai = QiuBai()qiubai.run()
總結
以上是生活随笔為你收集整理的爬虫——多线程糗事百科案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: phppage类封装分页功能_PHP封装
- 下一篇: celery异步执行任务在Django中