2
使用Mechanize提交登錄表單時遇到問題。例如,如果我需要登錄到到位桶:使用mechanize-ruby提交登錄表單時,我可以使用變量來表示字段名稱嗎?
a = Mechanize.new
a.get('https://bitbucket.org/') do |page|
login_page = a.click(page.link_with(text: 'Log In'))
my_page = login_page.form_with(action: '/account/signin/') do |f|
# The "username" and "password" below are the values of the "name" attribute of the two login form fields
f.username = 'MY_ACCOUNT_NAME'
f.password = 'MY_PASSWORD'
end.click_button
end
這是非常簡單的,但是,並不是所有的登錄表單有這兩個領域相同的「名稱」值。例如,WordPress的登錄表單使用「log」和「pwd」。這會使上面的代碼無效。
我想傳遞一些參數到這個方法中,以便它可以在不同的登錄表單上使用。 我試圖遵循「How to convert from a string to object attribute name?」但沒有成功:
# auth_info is a hash
def website_login(auth_info)
a = Mechanize.new
a.get(auth_info[:login_page_url]) do |page|
land_page = page.form_with(action: auth_info[:login_form_action]) do |f|
# Now I am stuck with these two lines
????????
????????
# I tried to do it like this. Not working.
f.instance_variable_set('@'+auth_info[:username_field_name], auth_info[:username])
f.instance_variable_set('@'+auth_info[:password_field_name], auth_info[:password])
end.click_button
end
end
真的很感激,如果有人可以幫忙。
不要將「已解決」添加到標題。創建一個答案並將其解決方案。堆棧溢出將允許您在寬限期後選擇該答案作爲解決方案,這將標記自動回答您的問題。 –
@theTinMan謝謝。 – blacktulip