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
4

1 回答 1

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

快乐刮

于 2013-02-25T15:27:17.327 回答