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

爬取豆瓣个人日记

阅读更多
看推特上有人推荐豆瓣上一位先生的日记,看了许久了,觉得果然不错。最近正好在玩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文件,可以慢慢品味。
我把这些文件打包传上来了,对代码不感兴趣但对文章感兴趣的同学可以看看

ps:本人是java党,所以代码写的像java一般还望大家见谅啊
分享到:
评论

相关推荐

    实战小项目:爬取豆瓣有关张国荣的日记(并作数据分析)

    实战小项目:爬取豆瓣有关张国荣的日记(并作数据分析) def get_main(self): mains=[] print u'\n',u'正在解析页面...' for i in range(1020,2001,20): response=self.get_source(url='...

    python爬虫-爬虫项目实战之爬取豆瓣有关张国荣日记.zip

    本教程将通过一个具体的实战项目——爬取豆瓣有关张国荣的日记,来深入理解Python爬虫的工作原理和实现方法。 首先,我们需要了解Python爬虫的基本构成。通常,一个简单的爬虫包括以下几个部分:请求(Request)、...

    Python爬虫项目之爬取豆瓣有关张国荣的日记.zip

    在本项目中,我们将深入探讨如何使用Python进行网络爬虫,特别关注于爬取豆瓣网站上与著名歌手张国荣相关的日记。这个项目旨在教授初学者如何构建一个基本的网络爬虫,同时也为有一定基础的开发者提供实战经验。我们...

    爬取豆瓣关于某博主所有日记的python爬虫代码

    在当前的信息时代,数据的抓取和...通过本文的介绍,我们已经对如何编写一个用于爬取豆瓣博主所有日记的Python爬虫程序有了基本的了解。这不仅是一个技术实现的过程,更是一个学习和理解网络数据抓取技术的实践机会。

    数据爬取调研1.91

    豆瓣【1】ID号或者字符串【2】【6】【8】【9】能从这两个列表获得所有好友的ID号【10】广播,一个豆瓣活动的日志,也有一些类似微博的短消息【11】豆瓣小组,

Global site tag (gtag.js) - Google Analytics