#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 + "秒"
首先聲明一個Queue隊列,然后往隊列中添加文章列表頁,以便后面可以從這些列表頁中提取文章鏈接,另外queue聲明成全局變量($),以便在函數(shù)中也可以訪問到。
#程序開始的時間
$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ù)。
ruby中,獲取網(wǎng)頁的方法用Net::HTTP模塊和OpenURI模塊。OpenURI模塊最簡單,可以直徑將指定網(wǎng)頁當(dāng)成普通文件一樣進行操作。