主頁 > 知識庫 > Ruby中使用多線程隊列(Queue)實現(xiàn)下載博客文章保存到本地文件

Ruby中使用多線程隊列(Queue)實現(xiàn)下載博客文章保存到本地文件

熱門標(biāo)簽:百度AI接口 呼叫中心市場需求 語音系統(tǒng) 電話運(yùn)營中心 硅谷的囚徒呼叫中心 企業(yè)做大做強(qiáng) 客戶服務(wù) Win7旗艦版

Ruby:多線程下載博客文章到本地的完整代碼

復(fù)制代碼 代碼如下:

#encoding:utf-8
require 'net/http'
require 'thread'
require 'open-uri'
require 'nokogiri'
require 'date'

$queue = Queue.new
#文章列表頁數(shù)
page_nums = 8
page_nums.times do |num|
  $queue.push("http://www.cnblogs.com/hongfei/default.html?page="+num.to_s)
end

threads = []
#獲取網(wǎng)頁源碼
def get_html(url)
  html = ""
  open(url) do |f|
    html = f.read
  end
  return html
end

def fetch_links(html)
  doc = Nokogiri::HTML(html)
  #提取文章鏈接
  doc.xpath('//div[@class="postTitle"]/a').each do |link|
    href = link['href'].to_s
    if href.include?"html"
      #add work to the  queue
      $queue.push(link['href'])
    end
  end
end

def save_to(save_to,content)
  f = File.new("./"+save_to+".html","w+")
  f.write(content)
  f.close()
end

#程序開始的時間
$total_time_begin = Time.now.to_i

#開辟的線程數(shù)
threadNums = 10
threadNums.times do
  threadsThread.new do
    until $queue.empty?
      url = $queue.pop(true) rescue nil
      html = get_html(url)
      fetch_links(html)
      if !url.include?"?page"
        title = Nokogiri::HTML(html).css('title').text
        puts "["+ Time.now.strftime("%H:%M:%S") + "]「" + title + "」" + url
        save_to("pages/" + title.gsub(/\//,""),html) if url.include?".html"
      end
    end
  end
end
threads.each{|t| t.join}

#程序結(jié)束的時間
$total_time_end = Time.now.to_i
puts "線程數(shù):" + threadNums.to_s
puts "執(zhí)行時間:" + ($total_time_end - $total_time_begin).to_s + "秒"

多線程部分講解

復(fù)制代碼 代碼如下:

$queue = Queue.new
#文章列表頁數(shù)
page_nums = 8
page_nums.times do |num|
  $queue.push("http://www.cnblogs.com/hongfei/default.html?page="+num.to_s)
end

首先聲明一個Queue隊列,然后往隊列中添加文章列表頁,以便后面可以從這些列表頁中提取文章鏈接,另外queue聲明成全局變量($),以便在函數(shù)中也可以訪問到。

我的曾是土木人博客文章列表總共有8頁,所以需要實現(xiàn)給page_nums賦值為8

復(fù)制代碼 代碼如下:

#開辟的線程數(shù)
threadNums = 10
threadNums.times do
  threadsThread.new do
    until $queue.empty?
      url = $queue.pop(true) rescue nil
      html = get_html(url)
      fetch_links(html)
      if !url.include?"?page"
        title = Nokogiri::HTML(html).css('title').text
        puts "["+ Time.now.strftime("%H:%M:%S") + "]「" + title + "」" + url
        save_to("pages/" + title.gsub(/\//,""),html) if url.include?".html"
      end
    end
  end
end
threads.each{|t| t.join}

通過Thread.new來創(chuàng)建線程

創(chuàng)建線程后,會進(jìn)入until $queue.empty?循環(huán),直到任務(wù)隊列為空(即:沒有要采集的網(wǎng)址了)
開辟的線程,每次都會從任務(wù)隊列(queue)取到一個url,并通過get_html函數(shù)獲取網(wǎng)頁源碼
由于任務(wù)隊列中的url有分頁url和文章url兩種,所以要進(jìn)行區(qū)分。
如果是分頁url(url中含有“?page”),就直接提取文章鏈接。
如果是文章url,就保存到本地(save_to(),文件名為文章title)
在循環(huán)體外,創(chuàng)建線程完畢后,需要將創(chuàng)建的線程執(zhí)行Thread#join方法,以便讓主線程等待,
直到所有的線程執(zhí)行完畢才結(jié)束主線程

代碼執(zhí)行時間統(tǒng)計

復(fù)制代碼 代碼如下:

#程序開始的時間
$total_time_begin = Time.now.to_i
#執(zhí)行過程

#程序結(jié)束的時間
$total_time_end = Time.now.to_i
puts "執(zhí)行時間:" + ($total_time_end - $total_time_begin).to_s + "秒"

TIme模塊的#now方法可以獲取當(dāng)前時間,然后使用to_i,可以將當(dāng)前時間轉(zhuǎn)換成從1970年1月1日00:00:00 UTC開始所經(jīng)過的秒數(shù)。

獲取網(wǎng)頁源碼

復(fù)制代碼 代碼如下:

#獲取網(wǎng)頁源碼
def get_html(url)
  html = ""
  open(url) do |f|
    html = f.read
  end
  return html
end

ruby中,獲取網(wǎng)頁的方法用Net::HTTP模塊和OpenURI模塊。OpenURI模塊最簡單,可以直徑將指定網(wǎng)頁當(dāng)成普通文件一樣進(jìn)行操作。

執(zhí)行結(jié)果:使用多線程采集130多篇文章,耗時15秒(單線程:47s左右)

您可能感興趣的文章:
  • Ruby中使用mechanize批量下載校內(nèi)網(wǎng)相冊照片
  • ruby實現(xiàn)的一個異步文件下載HttpServer實例
  • 比較不錯的關(guān)于ruby的電子書下載地址集合
  • windows和linux下Ruby的下載與安裝
  • Ruby使用eventmachine為HTTP服務(wù)器添加文件下載功能

標(biāo)簽:安康 濟(jì)南 山西 長沙 崇左 喀什 海南 山西

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Ruby中使用多線程隊列(Queue)實現(xiàn)下載博客文章保存到本地文件》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266