为什么Mechanize没有关注链接

时间:2013-02-25 15:11:55

标签: ruby mechanize

我正在尝试关注与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

1 个答案:

答案 0 :(得分:0)

您应该获取Charles(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

快乐刮刮