国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-10-26 19:25:24
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福贡县| 兰考县| 威信县| 金堂县| 伊川县| 牡丹江市| 闸北区| 黄浦区| 谢通门县| 新邵县| 华宁县| 博客| 肇源县| 嵊州市| 山东省| 永福县| 巫溪县| 遂昌县| 当雄县| 云安县| 翼城县| 南开区| 两当县| 徐汇区| 阿鲁科尔沁旗| 泸溪县| 曲松县| 岳池县| 乌什县| 和硕县| 双柏县| 射洪县| 新巴尔虎左旗| 武陟县| 神木县| 商丘市| 玉溪市| 景宁| 古交市| 上饶县| 方城县|