爬虫——多线程糗事百科案例
生活随笔
收集整理的這篇文章主要介紹了
爬虫——多线程糗事百科案例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Queue(隊(duì)列對(duì)象)
Queue是python中的標(biāo)準(zhǔn)庫(kù),可以直接import Queue引用;隊(duì)列是線程間最常用的交換數(shù)據(jù)的形式
python下多線程的思考
對(duì)于資源,加鎖是個(gè)重要的環(huán)節(jié)。因?yàn)閜ython原生的list,dict等,都是not thread safe的。而Queue,是線程安全的,因此在滿足使用條件下,建議使用隊(duì)列
初始化: class Queue.Queue(maxsize) FIFO 先進(jìn)先出
包中的常用方法:
-
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í)間
創(chuàng)建一個(gè)“隊(duì)列”對(duì)象
- import Queue
- myqueue = Queue.Queue(maxsize = 10)
將一個(gè)值放入隊(duì)列中
- myqueue.put(10)
將一個(gè)值從隊(duì)列中取出
- 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的隊(duì)列self.html_str_queue = Queue() #放響應(yīng)的隊(duì)列self.content_list_queue = Queue() #放提取的數(shù)據(jù)的隊(duì)列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): # 發(fā)送請(qǐng)求,獲取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): # 實(shí)現(xiàn)主要邏輯thread_list = []# 1.url_listt_url = threading.Thread(target=self.get_url_list)thread_list.append(t_url)# 2.發(fā)送請(qǐng)求,獲取數(shù)據(jù)for i in range(3):t_parse = threading.Thread(target=self.parse_url)thread_list.append(t_parse)# 3.提取數(shù)據(jù)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) #設(shè)置為守護(hù)線程,守護(hù)線程:這個(gè)線程不重要,主線程結(jié)束,子線程結(jié)束t.start()for q in [self.url_queue,self.content_list_queue,self.html_str_queue]:q.join() #讓主線程等待著,知道隊(duì)列計(jì)數(shù)為0的時(shí)候,join失效print("主線程結(jié)束")if __name__ == '__main__':qiubai = QiuBai()qiubai.run()
總結(jié)
以上是生活随笔為你收集整理的爬虫——多线程糗事百科案例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: phppage类封装分页功能_PHP封装
- 下一篇: Linux环境变量配置的三个方法--/e