爬取豆瓣个人日记

看推特上有人推荐豆瓣上一位[url=http://www.douban.com/people/1272884/notes]先生的日记[/url],看了许久了,觉得果然不错。最近正好在玩Hpricot,便写了个小程序,把这位先生的个人日记全部爬了下来

require 'rubygems'
require 'hpricot'
require 'string'
require 'open-uri'
require 'fileutils'

def write_file(file_content,title)
path = "E:\\"
file_name = path+title+".txt"
file = File.open(file_name,"w+")
file.puts title
file.puts file_content
file.close
end

def get_content_and_title(target_url)
doc = Hpricot(open(target_url))
content = doc.search("pre.note")
title = doc.search("div.note-header")
write_file(content.inner_html.to_gbk,title.at("h3").inner_html.to_gbk)
end

def get_article_url(articles_url)
doc = Hpricot(open(articles_url))
ele = doc.search("div.article")
ele.each do |ab|
arr = ab.children
arr.each do |cd|
begin
attribute = cd.attributes['id']
rescue NoMethodError
end
if(not attribute.nil? and attribute.include? "note-")
det = attribute.split("-")
id = det[1]
url = "http://www.douban.com/note/"+id
get_content_and_title(url)
end
end
end
end

def get_pages(articles_url)
puts articles_url
doc = Hpricot(open(articles_url))
ele = doc.search("span.next")
get_article_url(articles_url)
next_page = ele.at("a")
while next_page
next_page_url = next_page.attributes["href"]
get_article_url(next_page_url)
get_pages(next_page_url)
end
end

get_article_url("http://www.douban.com/people/1272884/notes")

执行以上程序,可将风行水上先生的个人日记全部爬下来,每篇日记一个txt文件,可以慢慢品味。
我把这些文件打包传上来了,对代码不感兴趣但对文章感兴趣的同学可以看看 :D

ps:本人是java党,所以代码写的像java一般还望大家见谅啊
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值