2013-02-25 59 views
1

我想跟随Mechanize的链接,但它似乎并没有工作,语法看起来是正确的,我引用这个不正确,或者我需要做别的吗?为什么机械化不遵循链接

问题区域

agent.page.links_with(:text => 'VG278H')[2].click 

全码

require 'rubygems' 
require 'mechanize' 
require 'open-uri' 

agent = Mechanize.new 

agent.get ("http://icecat.biz/en/") 

#Show all form fields belonging to the first form 
form = agent.page.forms[0].fields 

#Enter VG278H into the text box lookup_text, submit the data 
agent.page.forms[0]["lookup_text"] = "VG278H" 
agent.page.forms[0].submit #Results of this is stored in Mechanize agent.page object 

#Call agent.page with our results and assign them to a variable page 
page = agent.page 

agent.page.links_with(:text => 'VG278H')[2].click 

doc = page.parser 
puts doc 

回答

0

你应该抓住(http://www.charlesproxy.com/)查尔斯的副本或东西,可以让你观看,当您提交表单,会发生什么从您的浏览器。无论如何,你的问题是,这部分:

agent.page.forms[0]["lookup_text"] = "VG278H" 
agent.page.forms[0].submit 

正在恢复,看起来像这样一个HTML片段:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script>self.location.href="http://icecat.us/index.cgi?language=en&new_search=1&lookup_text=VG278H"</script> 

所以你确实需要直接调用此或报废了的self.location。 href和有你的代理执行GET:

page = agent.get("http://icecat.us/index.cgi?language=en&new_search=1&lookup_text=VG278H") 

如果你要做到这一点,这个工程:

require 'rubygems' 
require 'mechanize' 
require 'open-uri' 

agent = Mechanize.new 

agent.get ("http://icecat.biz/en/") 

page = agent.get("http://icecat.us/index.cgi?language=en&new_search=1&lookup_text=VG278H") 

page = page.links_with(:text => 'VG278H')[2].click 

doc = page.parser 
puts doc 

快乐刮

+0

上面的代码给出了我的原始代码相同的结果,是你的预期结果? – Ninja2k 2013-02-25 16:19:47

+0

真的吗?我不明白这怎么可能。与您发布的内容相比,您是否完全按照书面形式进行尝试?你的代码失败:tmp/s1.rb:19:'

':未定义的方法'点击'为nil:NilClass(NoMethodError),我的代码返回结果页面。 – rainkinz 2013-02-25 16:24:28

+0

哎呀对不起,你是对的我没有粘贴正确的代码!更正(我忽略了这一点:page = page.links_with(:text =>'VG278H')[2] .click) – rainkinz 2013-02-25 16:29:11