簡體   English   中英

使用Ruby和Mechanize填寫遠程登錄表單的謎團

[英]Using Ruby and Mechanize to fill in a remote login form mystery

我正在嘗試實現一個Ruby腳本,該腳本將接收用戶名和密碼,然后繼續在另一個網站上的登錄表單上填寫帳戶詳細信息,然后返回,然后按照鏈接檢索帳戶歷史記錄。 為此,我使用的是Mechanize gem。

我一直在關注這里的例子但我似乎無法讓它發揮作用。 我已經大大簡化了這一點,試圖讓它在部分工作,但一個假設的簡單填寫表格正在阻礙我。

這是我的代碼:

# script gets called with a username and password for the site
require 'mechanize'


#create a mechanize instant
agent = Mechanize.new 

agent.get('https://mysite/Login.aspx') do |login_page|

    #fill in the login form on the login page
    loggedin_page = login_page.form_with(:id => 'form1') do |form|
        username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
        username_field.value = ARGV[0]
        password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
        password_field.value = ARGV[1]


        button = form.button_with(:id => 'ContentPlaceHolder1_btnlogin')
    end.submit(form , button)

    #click the View my history link
    #account_history_page = loggedin_page.click(home_page.link_with(:text => "View My History"))

    ####TEST to see if i am actually making it past the login page
    #### and that the View My History link is now visible amongst the other links on the page
    loggedin_page.links.each do |link|
        text = link.text.strip
        next unless text.length > 0
        puts text if text == "View My History"
    end
    ##TEST 

end

終端錯誤消息:

stackqv2.rb:19:in `block in <main>': undefined local variable or method `form' for main:Object (NameError)
from /usr/local/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize.rb:409:in `get'
from stackqv2.rb:8:in `<main>'

您不需要將form作為參數傳遞即可submit button也是可選的。 嘗試使用以下內容:

loggedin_page = login_page.form_with(:id => 'form1') do |form|
    username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
    username_field.value = ARGV[0]
    password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
    password_field.value = ARGV[1]
end.submit

如果您確實需要指定用於提交表單的按鈕,請嘗試以下操作:

form = login_page.form_with(:id => 'form1')
username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
username_field.value = ARGV[0]
password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
password_field.value = ARGV[1]

button = form.button_with(:id => 'ContentPlaceHolder1_btnlogin')
loggedin_page = form.submit(button)

這是一個范圍問題:

page.form do |form|
  # this block has its own scope
  form['foo'] = 'bar' # <- ok, form is defined inside this block
end

puts form # <- error, form is not defined here

ramblex的建議是不要在你的表格中使用一個塊,我同意,這樣就不那么混亂了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM