2013-02-25 42 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