好久没有写ruby代码了,手有点生,今年准备多练练~
话说MM都喜欢看小说,网上连载的一直下一页下一页的点也不方便,于是就想到用代码把小说都抓取下来。html分析工具用的是hpricot。
require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'fileutils'
def wri
url = "http://www.yqxs.com/data/book2/ZfUAt35561/book35561_"
(1..22).each do |page|
sub_url = url+page.to_s+".html"
get_novel(sub_url)
end
end
def get_novel(target_url)
puts target_url
doc = Hpricot(open(target_url))
ele = doc.search("div[@id=content]")
write_file(ele.inner_html,"test")
end
def write_file(file_content,title)
path = "E:\\"
file_name = path+title+".html"
file = File.open(file_name,"a")
file.puts file_content
file.close
end
wri
Hpricot挺好用,可以根据css的class来找,还可以根据id来找。
ele = doc.search("div[@id=content]")
就是找到id是content的div
就这样吧,简单记录下。