Ruby中的Mechanize的使用教程
Ruby中实现网页抓取,一般用的是mechanize,使用非常简单。
安装
sudo gem install mechanize
抓取网页
require 'rubygems' require 'mechanize' agent = Mechanize.new page = agent.get('http://google.com/')
模拟点击事件
page = agent.page.link_with(:text => 'News').click
模拟表单提交
google_form = page.form('f') google_form["q"] = 'ruby mechanize' page = agent.submit(google_form, google_form.buttons.first) pp page
分析页面,mechanize用的是nokogiri解析网页的,所以可以参照nokogiri的文档
table = page.search('a') text = table.inner_text puts text
有几点注意的地方: 如果需要先登录的网页,那么可以在网站先登录,登录后记录JSESSIONID,然后赋值给agent
cookie = Mechanize::Cookie.new("JSESSIONID", "BA58528B76124698AD033EE6DF12B986:-1") cookie.domain = "datamirror.csdb.cn" cookie.path = "/" agent.cookie_jar.add!(cookie)
如果需要保存网页,使用.save_as,(或许save也可以,我没试过)例如
agent.get("http://google.com").save_as
小技巧
puts Mechanize::AGENT_ALIASES 可以打印出所有可用的user_agent
puts Mechanize.instance_methods(false) 输出Mechanize模块的所有方法
puts Mechanize.instance_methods() 输出Mechanize模块的所有方法以及所继承的类的函数
Ruby中使用多线程队列(Queue)实现下载博客文章保存到本地文件
Ruby:多线程下载博客文章到本地的完整代码#encoding:utf-8require'net/http'require'thread'require'open-uri'require'nokogiri'require'date'$queue=Queue.new#文章列表页数page_nums=8pa
Ruby中用线程实现经典的生产者消费者问题代码实例
示例代码:require"thread"puts"ProAndCon"queue=Queue.new#用队列Queue实现线程同步producer=Thread.newdo10.timesdo|i|sleeprand(i)#让线程睡眠一段时间queueiputs"#{i}produced"endendcon
Ruby中常用的字符串处理函数使用实例
1.返回字符串的长度str.length=integer2.判断字符串中是否包含另一个串str.includeother_str=trueorfalse"hello".include"lo"#=true"hello".include"ol"#=false"hello".includeh#=true3.字
标签:网页,的是,线程,字符串,队列