ruby - 为什么 Mechanize 不遵循链接

标签 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

最佳答案

您应该获取一份 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 并让您的代理执行获取:
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

快乐刮痧

关于ruby - 为什么 Mechanize 不遵循链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070124/

相关文章:

mysql - rails : Insert a lot of HTML code through migration to the database

Ruby If Elsif Else block 语法

Perl WWW::Mechanize 和 cookies

windows - 使用 Strawberry(可移植)Perl(适用于 Windows 7)安装 Mechanize 时遇到问题

python - 将列表传递给 HTML 表单 Python

javascript - 如何将 Ruby 编译为 Javascript?

ruby - OS X 中内置的 Ruby 扩展可以在 Linux 上运行吗?

ruby-on-rails - 稍后在 Perform_later ActiveJob 上设置 stub

python - 尝试 .read() 时,Mechanze 表单提交会导致响应 'Assertion Error'

perl - 为什么我的 Perl 脚本无法打印 cookie 值?