最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python如何使用隊列方式實現(xiàn)多線程爬蟲

 更新時間:2020年05月12日 10:32:02   作者:Norni  
這篇文章主要介紹了Python如何使用隊列方式實現(xiàn)多線程爬蟲,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

說明:糗事百科段子的爬取,采用了隊列和多線程的方式,其中關(guān)鍵點是Queue.task_done()、Queue.join(),保證了線程的有序進行。

代碼如下

import requests
from lxml import etree
import json
from queue import Queue
import threading

class Qsbk(object):
  def __init__(self):
    self.headers = {
      "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
      "Referer": "https://www.qiushibaike.com/"
    }
    # 實例化三個隊列,用來存放內(nèi)容
    self.url_queue = Queue()
    self.html_queue = Queue()
    self.content_queue = Queue()

  def get_total_url(self):
    """
    獲取了所有的頁面url,并且返回url_list
    return:url_list
    現(xiàn)在放入url_queue隊列中保存
    """
    url_temp = "https://www.qiushibaike.com/text/page/{}/"
    url_list = list()
    for i in range(1,13):
      # url_list.append(url_temp.format(i))
      # 將生成的url放入url_queue隊列
      self.url_queue.put(url_temp.format(i))

  def parse_url(self):
    """
    發(fā)送請求,獲取響應(yīng),同時etree處理html
    """
    while self.url_queue.not_empty:
      # 判斷非空,為空時結(jié)束循環(huán)

      # 從隊列中取出一個url
      url = self.url_queue.get()
      print("parsing url:",url)
      # 發(fā)送請求
      response = requests.get(url,headers=self.headers,timeout=10)
      # 獲取html字符串
      html = response.content.decode()
      # 獲取element類型的html
      html = etree.HTML(html)
      # 將生成的element對象放入html_queue隊列
      self.html_queue.put(html)
      # Queue.task_done() 在完成一項工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊列發(fā)送一個信號
      self.url_queue.task_done()

  def get_content(self):
    """
    解析網(wǎng)頁內(nèi)容,獲取想要的信息
    """
    while self.html_queue.not_empty:
      items = list()
      html = self.html_queue.get()
      total_div = html.xpath("http://div[@class='col1 old-style-col1']/div")
      for i in total_div:

        author_img = i.xpath(".//a[@rel='nofollow']/img/@src")
        author_img = "https"+author_img[0] if len(author_img)>0 else None

        author_name = i.xpath(".//a[@rel='nofollow']/img/@alt")
        author_name = author_name[0] if len(author_name)>0 else None

        author_href = i.xpath("./a/@href")
        author_+author_href[0] if len(author_href)>0 else None

        author_gender = i.xpath("./div[1]/div/@class")
        author_gender = author_gender[0].split(" ")[-1].replace("Icon","").strip() if len(author_gender)>0 else None

        author_age = i.xpath("./div[1]/div/text()")
        author_age = author_age[0] if len(author_age)>0 else None

        content = i.xpath("./a/div/span/text()")
        content = content[0].strip() if len(content)>0 else None

        content_vote = i.xpath("./div[@class='stats']/span[@class='stats-vote']/i/text()")
        content_vote = content_vote[0] if len(content_vote)>0 else None

        content_comment_numbers = i.xpath("./div[@class='stats']/span[@class='stats-comments']/a/i/text()")
        content_comment_numbers = content_comment_numbers[0] if len(content_comment_numbers)>0 else None

        item = {
          "author_name":author_name,
          "author_age" :author_age,
          "author_gender":author_gender,
          "author_img":author_img,
          "author_href":author_href,
          "content":content,
          "content_vote":content_vote,
          "content_comment_numbers":content_comment_numbers,
        }
        items.append(item)
      self.content_queue.put(items)
      # task_done的時候,隊列計數(shù)減一
      self.html_queue.task_done()

  def save_items(self):
    """
    保存items
    """
    while self.content_queue.not_empty:
      items = self.content_queue.get()
      with open("quishibaike.txt",'a',encoding='utf-8') as f:
        for i in items:
          json.dump(i,f,ensure_ascii=False,indent=2)
      self.content_queue.task_done()

  def run(self):
    # 獲取url list
    thread_list = list()
    thread_url = threading.Thread(target=self.get_total_url)
    thread_list.append(thread_url)

    # 發(fā)送網(wǎng)絡(luò)請求
    for i in range(10):
      thread_parse = threading.Thread(target=self.parse_url)
      thread_list.append(thread_parse)

    # 提取數(shù)據(jù)
    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:
      # 為每個進程設(shè)置為后臺進程,效果是主進程退出子進程也會退出
      t.setDaemon(True)
      t.start()
    
    # 讓主線程等待,所有的隊列為空的時候才能退出
    self.url_queue.join()
    self.html_queue.join()
    self.content_queue.join()


if __name__=="__main__":
  obj = Qsbk()
  obj.run()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • pycharm指定python路徑過程詳解

    pycharm指定python路徑過程詳解

    這篇文章主要介紹了Pycharm指定python路徑過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2023-04-04
  • 使用Python爬蟲庫requests發(fā)送請求、傳遞URL參數(shù)、定制headers

    使用Python爬蟲庫requests發(fā)送請求、傳遞URL參數(shù)、定制headers

    今天為大家介紹一下Python爬蟲庫requests的發(fā)送請求、傳遞URL參數(shù)、定制headers的基礎(chǔ)使用方法
    2020-01-01
  • OpenCV?光流Optical?Flow示例

    OpenCV?光流Optical?Flow示例

    這篇文章主要為大家介紹了OpenCV?光流Optical?Flow示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • Python使用面向?qū)ο蠓绞絼?chuàng)建線程實現(xiàn)12306售票系統(tǒng)

    Python使用面向?qū)ο蠓绞絼?chuàng)建線程實現(xiàn)12306售票系統(tǒng)

    目前python 提供了幾種多線程實現(xiàn)方式 thread,threading,multithreading ,其中thread模塊比較底層,而threading模塊是對thread做了一些包裝,可以更加方便的被使用
    2015-12-12
  • pandas讀取Excel批量轉(zhuǎn)換時間戳的實踐

    pandas讀取Excel批量轉(zhuǎn)換時間戳的實踐

    本文主要介紹了pandas讀取Excel批量轉(zhuǎn)換時間戳的實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • Python+Selenium實現(xiàn)自動填寫問卷

    Python+Selenium實現(xiàn)自動填寫問卷

    本文主要介紹了Python+Selenium實現(xiàn)自動填寫問卷,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • python動態(tài)進度條的實現(xiàn)代碼

    python動態(tài)進度條的實現(xiàn)代碼

    有時候我們需要使用print打印工作進度,正常使用print函數(shù)會導(dǎo)致刷屏的現(xiàn)象,本文通過實例代碼給大家介紹python動態(tài)進度條的實現(xiàn)方法,感興趣的朋友跟隨小編一起看看吧
    2019-07-07
  • Python實現(xiàn)自動清理電腦垃圾文件詳解

    Python實現(xiàn)自動清理電腦垃圾文件詳解

    經(jīng)常存在在我們的電腦中的垃圾文件主要是指系統(tǒng)在運行過程中產(chǎn)生的tmp臨時文件、日志文件、臨時備份文件等。本文將利用Python實現(xiàn)自動清理這些垃圾文件,需要的可以參考一下
    2022-03-03
  • python實現(xiàn)二分查找算法

    python實現(xiàn)二分查找算法

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)二分查找算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • python實現(xiàn)維吉尼亞加密法

    python實現(xiàn)維吉尼亞加密法

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)維吉尼亞加密法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03

最新評論

象山县| 翁牛特旗| 呼伦贝尔市| 玛沁县| 金坛市| 双桥区| 晋宁县| 湟源县| 治县。| 灵武市| 汉沽区| 化州市| 台北市| 邵东县| 鲁山县| 临猗县| 余姚市| 商河县| 饶阳县| 娱乐| 商河县| 都昌县| 伊春市| 乌海市| 应用必备| 城市| 都匀市| 贵阳市| 雷州市| 霍城县| 乌兰浩特市| 永丰县| 万盛区| 邵阳县| 成武县| 十堰市| 新巴尔虎右旗| 五华县| 湖南省| 南安市| 双城市|