使用Mechanize rubygem处理javascript onchange事件

使用Mechanize rubygem处理javascript onchange事件,javascript,ruby,onchange,mechanize-ruby,Javascript,Ruby,Onchange,Mechanize Ruby,我一直在尝试编写一个脚本,从我的大学网站获取结果。有人建议我使用Mechanize,它看起来确实很有前途 为了获得结果,必须首先输入卷号,然后选择会话。 使用Mechanize模拟第一部分很容易,但是对于第二部分,我遇到了问题,因为它实际上是一个JavaScript onchange事件 我阅读了JavaScript中的函数定义,这就是我到目前为止所想到的。Mechanize无法处理onchange事件,而且当我传递JavaScript函数手动更改的值时,返回相同的页面 下面是javaScrip

我一直在尝试编写一个脚本,从我的大学网站获取结果。有人建议我使用Mechanize,它看起来确实很有前途

为了获得结果,必须首先输入卷号,然后选择会话。 使用Mechanize模拟第一部分很容易,但是对于第二部分,我遇到了问题,因为它实际上是一个JavaScript onchange事件

我阅读了JavaScript中的函数定义,这就是我到目前为止所想到的。Mechanize无法处理onchange事件,而且当我传递JavaScript函数手动更改的值时,返回相同的页面

下面是javaScript代码

function __doPostBack(eventTarget, eventArgument) {
        var theform;
        if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
            theform = document.Form1;
        }
        else {
            theform = document.forms["Form1"];
        }
        theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
        theform.__EVENTARGUMENT.value = eventArgument;
        theform.submit();
    }
我在firebug中设置了一个断点,发现_EVENTTARGET的值为'Dt1',而_EVENTARGUMENT保持不变

我为此编写的ruby脚本是

require 'mechanize'

#set up the agent to mimic firefox on windows
agent = Mechanize.new
agent.keep_alive = true
agent.user_agent = 'Windows Mozilla'

page = agent.get('http://www.nitt.edu/prm/nitreg/ShowRes.aspx')

#using mechanize to get us past the first form presented
result_form = page.form('Form1')
result_form.TextBox1 = '205110018'

page = agent.submit( result_form, result_form.buttons.first )

#the second hurdle that we encounter,
#here i'm trying to get past the JavaScript by doing what it does manually
result_form = page.form('Form1')
result_form.field_with('Dt1').options.find { |opt| opt.value == '66' }.select
result_form.field_with( :name => '__EVENTTARGET' ).value = 'Dt1'

#here i should have got the page with the results
page = agent.submit(result_form)
pp page

谁能告诉我我做错了什么

看起来你已经开始工作了!尝试使用puts page.body而不是pp page,您将看到页面的内容。您可以使用Mechanize搜索功能从页面中刮取数据

此外,您还可以将该代码简化为:

result_form['__EVENTTARGET'] = 'Dt1'
result_form['Dt1'] = '66'

看起来你已经开始工作了!尝试使用puts page.body而不是pp page,您将看到页面的内容。您可以使用Mechanize搜索功能从页面中刮取数据

此外,您还可以将该代码简化为:

result_form['__EVENTTARGET'] = 'Dt1'
result_form['Dt1'] = '66'

使用puts page.body不起作用,它给了我类似的东西。您需要在浏览器中访问url才能了解我面临的问题。@nikhil我确实在浏览器中访问过,甚至运行Fiddler查看页面请求。这一切都很好。这不适用于使用puts page.body给我类似的东西。您需要在浏览器中访问url才能了解我面临的问题。@nikhil我确实在浏览器中访问过,甚至运行Fiddler查看页面请求。一切都很顺利。