使Mechanize处理来自任意POST的cookie(以编程方式登录网站) [英] Get Mechanize to handle cookies from an arbitrary POST (to log into a website programmatically)

查看:69
本文介绍了使Mechanize处理来自任意POST的cookie(以编程方式登录网站)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式登录 https://www.t-mobile.com/ .我的第一个想法是使用Mechanize提交登录表单:

I want to log into https://www.t-mobile.com/ programmatically. My first idea was to use Mechanize to submit the login form:

替代文字http://dl.dropbox.com /u/2792776/screenshots/2010-04-08_1440.png

但是,事实证明,这甚至不是真正的形式.相反,当您单击登录"时,一些javascript会获取字段的值,动态创建一个新表单,然后提交它.

However, it turns out that this isn't even a real form. Instead, when you click "Log in" some javascript grabs the values of the fields, creates a new form dynamically, and submits it.

登录"按钮HTML:

<button onclick="handleLogin(); return false;" class="btnBlue" id="myTMobile-login"><span>Log in</span></button>

handleLogin()函数:

function handleLogin() {
    if (ValidateMsisdnPassword()) { // client-side form validation logic
        var a = document.createElement("FORM");
        a.name = "form1";
        a.method = "POST";
        a.action = mytmoUrl; // defined elsewhere as https://my.t-mobile.com/Login/LoginController.aspx
        var c = document.createElement("INPUT");
        c.type = "HIDDEN";
        c.value = document.getElementById("myTMobile-phone").value; // the value of the phone number input field
        c.name = "txtMSISDN";
        a.appendChild(c);
        var b = document.createElement("INPUT");
        b.type = "HIDDEN";
        b.value = document.getElementById("myTMobile-password").value; // the value of the password input field
        b.name = "txtPassword";
        a.appendChild(b);
        document.body.appendChild(a);
        a.submit();
        return true
    } else {
        return false
    }
}

我可以通过使用Net::HTTP#post_form将表单数据发布到https://my.t-mobile.com/Login/LoginController.aspx来模拟此表单提交,但是我不知道如何将生成的Cookie放入Mechanize中,因此我可以继续抓取可用的UI登录.

I could simulate this form submission by POSTing the form data to https://my.t-mobile.com/Login/LoginController.aspx with Net::HTTP#post_form, but I don't know how to get the resultant cookie into Mechanize so I can continue to scrape the UI available when I'm logged in.

有什么想法吗?

推荐答案

您可以使用类似的方式登录并保存cookie,因此您无需再次执行该操作.当然,您需要提出自己的逻辑以直接将其发布,但这就是我使用Mechanize内置的cookie_jar方法保存cookie的方式.

You can use something like this to login and save the cookie so you won't have to do it again. Of course you will need to come up with your own logic to post it directly but this is how I use Mechanize's built in cookie_jar method to save cookies.

if !agent.cookie_jar.load('cookies.yml')
  page = agent.get('http://site.com')

  form = page.forms.last
  form.email = 'email'
  form.password = 'password'

  page = agent.submit(form)

  agent.cookie_jar.save_as('cookies.yml')
end

这篇关于使Mechanize处理来自任意POST的cookie(以编程方式登录网站)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆