Ruby中使用多線程隊列(Queue)實現下載部落格文章儲存到本地檔案_ruby專題

來源:互聯網
上載者:User

Ruby:多線程下載部落格文章到本地的完整代碼

複製代碼 代碼如下:

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

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

threads = []
#擷取網頁源碼
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

#開闢的線程數
threadNums = 10
threadNums.times do
  threads<<Thread.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}

#程式結束的時間
$total_time_end = Time.now.to_i
puts "線程數:" + threadNums.to_s
puts "執行時間:" + ($total_time_end - $total_time_begin).to_s + "秒"

多線程部分講解

複製代碼 代碼如下:

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

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

我的曾是土木人部落格文章列表總共有8頁,所以需要實現給page_nums賦值為8

複製代碼 代碼如下:

#開闢的線程數
threadNums = 10
threadNums.times do
  threads<<Thread.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來建立線程

建立線程後,會進入until $queue.empty?迴圈,直到任務隊列為空白(即:沒有要採集的網址了)
開闢的線程,每次都會從任務隊列(queue)取到一個url,並通過get_html函數擷取網頁源碼
由於任務隊列中的url有分頁url和文章url兩種,所以要進行區分。
如果是分頁url(url中含有“?page”),就直接提取文章連結。
如果是文章url,就儲存到本地(save_to(),檔案名稱為文章title)
在迴圈體外,建立線程完畢後,需要將建立的線程執行Thread#join方法,以便讓主線程等待,
直到所有的線程執行完畢才結束主線程

代碼執行時間統計

複製代碼 代碼如下:

#程式開始的時間
$total_time_begin = Time.now.to_i
#執行過程

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

TIme模組的#now方法可以擷取目前時間,然後使用to_i,可以將目前時間轉換成從1970年1月1日00:00:00 UTC開始所經過的秒數。

擷取網頁源碼

複製代碼 代碼如下:

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

ruby中,擷取網頁的方法用Net::HTTP模組和OpenURI模組。OpenURI模組最簡單,可以直徑將指定網頁當成普通檔案一樣進行操作。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.