`
kaka2008
  • 浏览: 91853 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用ruby来抓取小说

    博客分类:
  • ruby
阅读更多
   好久没有写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

就这样吧,简单记录下。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics