六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 101|回复: 0

使用ruby来抓取小说

[复制链接]

升级  17.33%

18

主题

18

主题

18

主题

秀才

Rank: 2

积分
76
 楼主| 发表于 2013-2-7 20:39:18 | 显示全部楼层 |阅读模式
好久没有写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)   endenddef get_novel(target_url)puts target_urldoc = Hpricot(open(target_url))ele = doc.search("div[@id=content]")write_file(ele.inner_html,"test")enddef write_file(file_content,title)  path = "E:\\"  file_name = path+title+".html"  file = File.open(file_name,"a")  file.puts file_content  file.closeendwri   
Hpricot挺好用,可以根据css的class来找,还可以根据id来找。
  ele = doc.search("div[@id=content]")
就是找到id是content的div

就这样吧,简单记录下。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表