黑松山资源网 Design By www.paidiu.com

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"+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""
        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"+num.to_s)
end

首先声明一个Queue队列,然后往队列中添加文章列表页,以便后面可以从这些列表页中提取文章链接,另外queue声明成全局变量($),以便在函数中也可以访问到。

我的曾是土木人博客文章列表总共有8页,所以需要实现给page_nums赋值为8
复制代码 代码如下:
#开辟的线程数
threadNums = 10
threadNums.times do
  threads<<Thread.new do
    until $queue.empty""
        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"codetitle">复制代码 代码如下:
#程序开始的时间
$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左右)

Ruby中使用多线程队列(Queue)实现下载博客文章保存到本地文件

黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。