網絡爬蟲--15.【糗事百科實戰】多線程實現

文章目錄

  • 一. Queue(隊列對象)
  • 二. 多線程示意圖
  • 三. 代碼示例

一. Queue(隊列對象)

Queue是python中的標準庫,可以直接import Queue引用;隊列是線程間最常用的交換數據的形式

python下多線程的思考

對于資源,加鎖是個重要的環節。因為python原生的list,dict等,都是not thread safe的。而Queue,是線程安全的,因此在滿足使用條件下,建議使用隊列

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

  2. 包中的常用方法:
    Queue.qsize() 返回隊列的大小
    Queue.empty() 如果隊列為空,返回True,反之False
    Queue.full() 如果隊列滿了,返回True,反之False
    Queue.full 與 maxsize 大小對應
    Queue.get([block[, timeout]])獲取隊列,timeout等待時間

  3. 創建一個“隊列”對象
    import queue
    myqueue = queue.Queue(maxsize = 10)

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

  5. 將一個值從隊列中取出

myqueue.get()

二. 多線程示意圖

在這里插入圖片描述

三. 代碼示例

# coding=utf-8
import requests
from lxml import etree
import json
from queue import Queue
import threadingclass Qiubai:def __init__(self):self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWeb\Kit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}self.url_queue = Queue()   #實例化三個隊列,用來存放內容self.html_queue =Queue()self.content_queue = Queue()def get_total_url(self):'''獲取了所有的頁面url,并且返回urllistreturn :list'''url_temp = 'https://www.qiushibaike.com/8hr/page/{}/'# url_list = []for i in range(1,36):# url_list.append(url_temp.format(i))self.url_queue.put(url_temp.format(i))def parse_url(self):'''一個發送請求,獲取響應,同時etree處理html'''while self.url_queue.not_empty:url = self.url_queue.get()print("parsing url:",url)response = requests.get(url,headers=self.headers,timeout=10) #發送請求html = response.content.decode() #獲取html字符串html = etree.HTML(html) #獲取element 類型的htmlself.html_queue.put(html)self.url_queue.task_done()def get_content(self):''':param url::return: 一個list,包含一個url對應頁面的所有段子的所有內容的列表'''while self.html_queue.not_empty:html = self.html_queue.get()total_div = html.xpath('//div[@class="article block untagged mb15"]') #返回divelememtn的一個列表items = []for i in total_div: #遍歷div標槍,獲取糗事百科每條的內容的全部信息author_img = i.xpath('./div[@class="author clearfix"]/a[1]/img/@src')author_img = "https:" + author_img[0] if len(author_img) > 0 else Noneauthor_name = i.xpath('./div[@class="author clearfix"]/a[2]/h2/text()')author_name = author_name[0] if len(author_name) > 0 else Noneauthor_href = i.xpath('./div[@class="author clearfix"]/a[1]/@href')author_href = "https://www.qiushibaike.com" + author_href[0] if len(author_href) > 0 else Noneauthor_gender = i.xpath('./div[@class="author clearfix"]//div/@class')author_gender = author_gender[0].split(" ")[-1].replace("Icon", "") if len(author_gender) > 0 else Noneauthor_age = i.xpath('./div[@class="author clearfix"]//div/text()')author_age = author_age[0] if len(author_age) > 0 else Nonecontent = i.xpath('./a[@class="contentHerf"]/div/span/text()')content_vote = i.xpath('./div[@class="stats"]/span[1]/i/text()')content_vote = content_vote[0] if len(content_vote) > 0 else Nonecontent_comment_numbers = i.xpath('./div[@class="stats"]/span[2]/a/i/text()')content_comment_numbers = content_comment_numbers[0] if len(content_comment_numbers) > 0 else Nonehot_comment_author = i.xpath('./a[@class="indexGodCmt"]/div/span[last()]/text()')hot_comment_author = hot_comment_author[0] if len(hot_comment_author) > 0 else Nonehot_comment = i.xpath('./a[@class="indexGodCmt"]/div/div/text()')hot_comment = hot_comment[0].replace("\n:", "").replace("\n", "") if len(hot_comment) > 0 else Nonehot_comment_like_num = i.xpath('./a[@class="indexGodCmt"]/div/div/div/text()')hot_comment_like_num = hot_comment_like_num[-1].replace("\n", "") if len(hot_comment_like_num) > 0 else Noneitem = dict(author_name=author_name,author_img=author_img,author_href=author_href,author_gender=author_gender,author_age=author_age,content=content,content_vote=content_vote,content_comment_numbers=content_comment_numbers,hot_comment=hot_comment,hot_comment_author=hot_comment_author,hot_comment_like_num=hot_comment_like_num)items.append(item)self.content_queue.put(items)self.html_queue.task_done()  #task_done的時候,隊列計數減一def save_items(self):'''保存items:param items:列表'''while self.content_queue.not_empty:items = self.content_queue.get()f = open("qiubai.txt","a")for i in items:json.dump(i,f,ensure_ascii=False,indent=2)# f.write(json.dumps(i))f.close()self.content_queue.task_done()def run(self):# 1.獲取url list# url_list = self.get_total_url()thread_list = []thread_url = threading.Thread(target=self.get_total_url)thread_list.append(thread_url)#發送網絡請求for i in range(10):thread_parse = threading.Thread(target=self.parse_url)thread_list.append(thread_parse)#提取數據thread_get_content = threading.Thread(target=self.get_content)thread_list.append(thread_get_content)#保存thread_save = threading.Thread(target=self.save_items)thread_list.append(thread_save)for t in thread_list:t.setDaemon(True)  #為每個進程設置為后臺進程,效果是主進程退出子進程也會退出t.start()          #為了解決程序結束無法退出的問題## for t in thread_list:#     t.join()self.url_queue.join()   #讓主線程等待,所有的隊列為空的時候才能退出self.html_queue.join()self.content_queue.join()if __name__ == "__main__":qiubai = Qiubai()qiubai.run()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/451996.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/451996.shtml
英文地址,請注明出處:http://en.pswp.cn/news/451996.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

淺談:國內軟件公司為何無法做大做強?

縱覽,國內比較大的軟件公司(以下統一簡稱"國軟"),清一色都是做政府項目的(他們能做大的原因我就不用說了吧),真正能做大的國軟又有幾家呢?這是為什么呢? 今天風吹就給大家簡單分析下: 1."作坊"式管理 "作坊"往往是效率最高的,國軟幾乎都是從作…

Java SE、Java EE、Java ME三者的區別

說得簡單點 Java SE 是做電腦上運行的軟件。 Java EE 是用來做網站的-(我們常見的JSP技術) Java ME 是做手機軟件的。 1. Java SE(Java Platform,Standard Edition)。Java SE 以前稱為 J2SE。它允許開發和部署在桌面、…

FileBeats安裝

FileBeats安裝 FileBeats官方下載鏈接: https://www.elastic.co/downloads/beats/filebeat 也可以直接使用以下命令下載(文章下載目錄一概為/home/tools, 解壓后文件夾放到 /home/apps下) wget https://artifacts.elastic.co/downloads/beats…

《程序員代碼面試指南》第三章 二叉樹問題 二叉樹節點間的最大距離問題

題目 二叉樹節點間的最大距離問題 java代碼 package com.lizhouwei.chapter3;/*** Description:二叉樹節點間的最大距離問題* Author: lizhouwei* CreateDate: 2018/4/16 19:33* Modify by:* ModifyDate:*/ public class Chapter3_20 {public int maxDistance(Node head) {int[…

MySQL中函數CONCAT及GROUP_CONCAT 對應oracle中的wm_concat

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 一、CONCAT()函數 CONCAT()函數用于將多個字符串連接成一個字符串。 使用數據表Info作為…

網絡爬蟲--16.BeautifulSoup4

文章目錄一. BeautifulSoup4二. 解析實例三. 四大對象種類1. Tag2. NavigableString3. BeautifulSoup4. Comment四. 遍歷文檔樹1.直接子節點 :.contents .children 屬性1). .contents2). .children2. 所有子孫節點: .descendants 屬性3. 節點內容: .string 屬性五. …

Intel MKL 多線程設置

對于多核程序,多線程對于程序的性能至關重要。 下面,我們將對Intel MKL 有關多線程方面的設置做一些介紹: 我們提到MKL 支持多線程,它包括的兩個概念: 1>MKL 是線程安全的: MKL在設計時,就保…

【LA3415 訓練指南】保守的老師 【二分圖最大獨立集,最小割】

題意 Frank是一個思想有些保守的高中老師。有一次,他需要帶一些學生出去旅行,但又怕其中一些學生在旅行中萌生愛意。為了降低這種事情發生的概率,他決定確保帶出去的任意兩個學生至少要滿足下面四條中的一條。 1.身高相差大于40厘米 2.性別相…

行車記錄儀穩定方案:TC358778XBG:RGB轉MIPI DSI芯片,M-Star標配IC

原廠:Toshiba型號:TC358778XBG功能:TC358778XBG是一顆將RGB信號轉換成MIPI DSI的芯片,最高分辨率支持到1920x1200,其應用圖如下:產品特征:MIPI接口:(1)、支持…

java.sql.SQLException: 無法轉換為內部表示之解決

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 這個錯是因為 數據庫中字段類型和程序中該字段類型不一致。 比如程序將某字段當做Integer類型, 而數據庫存儲又使用另外一…

網絡爬蟲--17.【BeautifuSoup4實戰】爬取騰訊社招

文章目錄一.要求二.代碼示例一.要求 以騰訊社招頁面來做演示:http://hr.tencent.com/position.php?&start10#a 使用BeautifuSoup4解析器,將招聘網頁上的職位名稱、職位類別、招聘人數、工作地點、發布時間,以及每個職位詳情的點擊鏈接…

public static void main(String[] args)的理解

public:權限修飾符,權限最大。static:隨著MianDemo類的加載而加載,消失而消失。void: 沒有返回值main: 函數名,jvm識別的特殊函數名(String[] args):定義了一個字符串數組參數。這個字符串數組是保存運行main函數時輸入的參數的

Miller-Rabin素數測試

Miller-Rabin素數測試 給出一個小于1e18的數,問它是否為質數?不超過50組詢問。hihocoder 我是真的菜,為了不誤導他人,本篇僅供個人使用。 首先,一個1e18的數,樸素\(O(\sqrt{n})\)素數判定肯定爆炸。怎么辦呢…

throws Exception的意思

在方法聲明部分使用,表示該方法可能產生此異常,如果在方法聲明處使用了throws聲明異常,則該方法產生異常也不必捕獲,會直接把異常拋出到調用該方法的地方。

java list按照元素對象的指定多個字段屬性進行排序

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 直接提取重點代碼: /*** 把結果集合按時間字段排序,內部類重寫排序規則:* param list* return*/priv…

網絡爬蟲--18.python中的GIL(全局解釋器鎖)、多線程、多進程、并發、并行

參考文獻: python的GIL、多線程、多進程 并發和并行的區別? GIL(全局解釋器鎖)一看就懂的解釋! 多謝作者分享!

Socket和ServerSocket

對于即時類應用或者即時類的游戲,HTTP協議很多時候無法滿足于我們的需求。這會,Socket對于我們來說就非常實用了。下面是本次學習的筆記。主要分異常類型、交互原理、Socket、ServerSocket、多線程這幾個方面闡述。異常類型在了解Socket的內容之前&#…

徹底搞清楚Android中的 Attr

版權聲明:本文為sydMobile原創文章,轉載請務必注明出處! https://blog.csdn.net/sydMobile/article/details/79978187 相信這個詞對于Android開發者來說十分熟悉了,那么你對他到底有多了解呢? 回憶起我剛開始接觸Andr…

D. Relatively Prime Graph

Lets call an undirected graph G(V,E)G(V,E) relatively prime if and only if for each edge (v,u)∈E(v,u)∈E GCD(v,u)1GCD(v,u)1 (the greatest common divisor of vv and uu is 11). If there is no edge between some pair of vertices vv and uu then the value of GC…

解決 : org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 報錯: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.tanj.mapper.SendDeta…