【问题标题】:Mechanize getting stuck on Javascript redirect page机械化卡在 Javascript 重定向页面上
【发布时间】:2012-04-22 10:47:24
【问题描述】:

我在我的 Ruby on Rails 应用程序中使用 Mechanize 和 Nokogiri 来抓取我们的本地打印机管理面板,以检索打印机生命周期内的打印页数。

我有以下 rake 任务:

# Logs into printer admin page and retrieved counts.
require 'rubygems'
require 'mechanize'
require 'logger'

# Create a new mechanize object
agent = Mechanize.new

# Load the printer admin page
page = agent.get("http://192.168.1.126/index.html?lang=1")

# Select the form with an action of index.cqi
form = agent.page.form_with(:action => "index.cgi")
form.radiobuttons_with(:id => '0x3fdb24153404')[1]

# Submit the form
page = form.submit form.buttons.first

pp page

返回以下内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<script type="text/javascript">
<!--
window.onload=function(){setTimeout(function(){document.menu_link.submit();},0);}
//-->
</script>
</head>
<body>
<form name="menu_link" action="index.html" method="post" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="lang" value="1">
</form>
</body>
</html>

我似乎无法选择上述页面上的表单,并且脚本似乎停在该页面并且没有遵循重定向。

是否有处理此类重定向的标准方法?也许暂停脚本直到重定向发生?它会允许重定向工作吗?

任何指针将不胜感激!

【问题讨论】:

  • 第二页的表格怎么选?
  • 我刚刚选择了名为 menu_link 的表单。

标签: javascript ruby-on-rails-3 redirect nokogiri mechanize


【解决方案1】:

您有两个选择。要么:

  1. Submit the form manually
  2. 使用WatirSelenium

基本上 Mechanise 不会运行 javascript,因此您必须手动模拟 javascript 运行(选项 1)或自动化真正的浏览器来执行此操作(选项 2)

如果您只执行 POSTlang=1 而不是 get ,则选项 1 应该是双倍的,因为这就是表单所做的一切。

我猜是这样的:

page = agent.post('http://192.168.1.126/index.html', {
  "lang" => "1"
})

但我从未真正使用过 Mechanize。

【讨论】:

  • 我已经在登录页面 page = agent.get("http://192.168.1.126/index.html?lang=1") 中请求 lang=1,再次请求它会出现 404 错误。
  • 这不是get,你需要的是post
【解决方案2】:

您应该尝试在这样的重定向上添加关注

agent.follow_meta_refresh = true

此外,如果这是 javascript 控制的行为,那么您处于不利位置,因为 mechanize 无法遵循这一点。他不执行js。您必须在 js 中查看他是如何做到的,并在 mechanize 中模拟相同的调用。

但我认为你需要做的只是

agent.post <url>

因为他似乎在期待 post 方法。

有一个硬核替代方案:) 在 node.js 中使用 node-crawler https://github.com/joshfire/node-crawler 它可以从客户端页面服务器端评估javascript。

【讨论】:

  • 如果我做 agent.post "index.html" 它会让我回到登录页面?
  • 该 HTML 中没有元刷新,它是一个 js 表单提交,完全不同的机制
  • 指向 node.js 替代方案的链接已损坏。我认为它已移至此处github.com/sylvinus/node-crawler
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 2011-01-10
  • 2023-03-10
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多