写道
Nokogiri (鋸) is an HTML, XML, SAX, and Reader parser. Among Nokogiri’s many features is the ability to search documents via XPath or CSS3 selectors.
XML is like violence - if it doesn’t solve your problems, you are not using enough of it.
Nokogiri的解析能力+open-uri的网络访问想组合就可以用来抓取网络上的一些资源了,下面的这段代码用来抓取清杯浅酌这个wp博客。由于ruby代码写的比较java化,只能通过平时多写多看来提高自己的美感,高手请飘过。
require 'rubygems'
require 'nokogiri'
require 'open-uri'
desc "Fetch articles from http://xuzhuoer.com/"
task :fetch => :environment do
ids = Nokogiri::HTML(open("http://xuzhuoer.com/archives/"))
ids.css('.post li a').each_with_index do |link, index|
href = link.attr("href")
doc = Nokogiri::HTML(open(href))
# get the article's content & title & tag_list
content = doc.css('.post > .content').inner_html
title = doc.css('h1').text
tags = ""
doc.css('.post_info a').each do |tag|
tags << tag.text << " "
end
# create post and save it
@post = Post.create!(:body => content, :tag_list => tags.strip!, :title => title )
# get the article's comments
doc.css('#comments > .comment').each_with_index do |comment, index|
author = comment.css('.author').text
unless comment.css('a[@class="author"]').empty?
author_url = comment.css('a[@class="author"]').attr('href')
end
body = comment.css('.content p').text
# fetch the author's md5(email) to get gravatar
md5 = comment.css('img').attr('src').text[31...63]
# create & save comment
Comment.create!(:author => author, :author_url => author_url,
:body => body, :avatar_md5 => md5,
:commentable_type => "Post", :commentable_id => @post.id)
sleep(5)
end
sleep(rand(5))
end
end
如果抓取的网站资源需要登陆后才能看到,那么这个方法就显得无能为力了。不过加上Mechanize,结果就可能不一样了。mechazie能够模拟表单的提交并在以后的表单操作中自动设置cookie。
分享到:
相关推荐
Java抓取网络资源并插入数据库(附详细代码) 如有不懂处可加qq412546724
C#版本的网络爬虫,抓取网络资源 经过一些改进,如果想采集新闻、BBS等,还需要做一些解析规则
威奇托桥梁 使用Nokogiri从抓取的Wichita桥数据并保存到JSON文件。 例子 在查看有关在Google地图中绘制的数据的实时演示
查询某一网站的资源并获取其信息使之成为自己网站的资源
抓取网络数据包的实现方法、、、、、、、、、、、、、、、、、、、、、、、、、、、
利用网络嗅探实现抓取网络文件 利用网络嗅探实现抓取网络文件 利用网络嗅探实现抓取网络文件 利用网络嗅探实现抓取网络文件
用C++实现网络编程---抓取网络数据包的实现方法
《机械臂抓取从入门到实战》课程视频及配套资料 ...5.3 训练平面抓取网络 5.4 平面抓取网络仿真 6.1 机械臂上位机控制演示 6.2 基于ROS的手眼标定 6.3 实物抓取演示 6.4 ROS机械臂抓取代码详解 6.5 机械臂抓取流程总结
上传至服务器,抓取网络端口、线程日志、堆栈等内容。执行check.sh即可
华南理工大学计算机网络网络报文抓取与分析实验报告.pdf
抓取网络数据demo
C# 抓取TCP UDP网络数据包.zip亲测可用, 谢谢支持。
网络游戏-一种确定网络资源点的抓取频率的装置和方法.zip
抓取进程的网络数据工具抓取进程的网络数据工具
缠绕在Nokogiri DSL,由Nokogiri用于网络抓取。 安装 将此行添加到您的应用程序的Gemfile中: gem 'buzzsaw' 然后执行: $ bundle 或将其自己安装为: $ gem install buzzsaw 用法 Stretch.io用于DSL的就是这...
网络游戏-对网络资源进行抓取及更新消息推送的方法及系统.zip
利用python抓取网络图片的步骤: 1.根据给定的网址获取网页源代码 2.利用正则表达式把源代码中的图片地址过滤出来 3.根据过滤出来的图片地址下载网络图片
网络游戏-一种用于确定网络资源点的抓取频率的方法和装置.zip
VB6.0演示如何抓取网络数据包,截获网络包的例子,原型是一个网络原始数据包嗅探器的修正版代码,程序基于winsock API,支持TCP,UDP和ICMP三种协议数据的抓取,支持记录到文件等操作。抓取的数据中包括了IP 报头、...
数据抓取解决方案数据抓取解决方案数据抓取解决方案数据抓取解决方案