Ruby进修条记一 安装Ruby与Ruby的爬虫应用
最近终于空下来了,所以下个Ruby玩玩,安装Ruby很简朴,去官网下载一个一键 安装包既可,linux下的安装,各人Google下就有许多教程了.对付IDE网上说 NetBeans支持得很完美,可是因为本人较量喜欢Eclipse,所以照旧跟各人推荐 EasyEclipse for Ruby and Rails,虽然你可以选择只下RoR的插件而不弄个全新 的Eclipse.
以前一直在用Java写爬虫东西抓图片,对HttpClient包装,正则表达式处理惩罚那 个是累啊,就算弄好了东西类,有时候一会又想不起来放哪儿,但Ruby对方面包装 的就很强大,短短几十行代码就搞定了这一切:
页面获取和文件下载的要领.
util.rb:
require'net/http'
defquery_url(url)
returnNet::HTTP.get(URI.parse(url));
end
defsave_url(url,dir,filename)
filename=url[url.rindex('/')+1,url.length-1] iffilename==nil||filename.empty?
require'open-uri'
Dir.mkdir("#{dir}")ifdir!=nil&&!dir.empty? &&!FileTest.exist?(dir)
open(url)do|fin|
iftrue
File.new("#{dir}#{filename}","wb").close
open("#{dir}#{filename}","wb")do|fout|
whilebuf=fin.read(1024)do
fout.writebuf
STDOUT.flush
end
end
end
end
end
抓取图片的详细应用:
require "util" begin start_url = 'http://list.mall.taobao.com/1424/g-d-----40-0--1424.htm' while start_url != nil && !start_url.empty? do print "开始下载#{start_url}\n" content = query_url(start_url) next_page = content.scan(/ <a href="(.*?)" class="next-page"><span>下一页<\/span><\/a>/) next_url = nil next_url = next_page[0][0] if next_page != nil && next_page.length > 0 && next_page[0].length > 0 imgs = content.scan(/<img src="(http:\/\/img[\d].*?)" \/>/) for img in imgs url = img[0]; save_url(url,"d:\\mall\\",nil) end start_url = next_url; # break; end end
利用一天之后感受ruby的语法很自然,很好领略,上手较量容易,并且相关包封 装的也很好,确实较量适合拿来玩玩小措施.