Filling forms with `Mojo::UserAgent`
In the process of renewing a scraping script, I decided to replace WWW::Mechanize by Mojo::UserAgent. All is good until I have to fill a form in order to login: while the former uses
my $resp = $agent->submit_form(
form_number => 1,
fields => {
strLogin => $user,
strPwd => $passwd,
});
in the documentation of Mojo::UserAgent, all the POST example methods are always called directly passing the parameters. This is a bit more inconvenient, since I have to take into account all the details of the form I am filling (for example looking if the form is POST or GET).
Are there any other solutions or this is just the way it works?
Posted Jul 10, 2017, 7:30 PM UTC
To my mind, Mojo::UserAgent is a lower-level tool than WWW::Mechanize, so it's not surprising it doesn't offer all the convenience a crawler would. It's really a better-designed LWP::UserAgent than a replacement for WWW::Mechanize.
Why are you replacing WWW::Mechanize at all, out of curiousity?
Well, I recently discovered
Mojo::DOM, and that I could use it to replace my clunky use ofHTML::Parser, and I thought that I could go using just theMojoframework for all the tasks.Even if it is not as convenient for "clicking buttons" I am still thinking of going fully "Mojo-based"; I really like this framework.
Thanks for your comment, by the way!
Try Mechanize + Web::Query(::LibXML).
WQ is the best declarative HTML parser.
Nice, thanks!
Mojo::UserAgent is certainly usable for this task but as you noted, it only does the requests you specify; it doesn't contain the logic of WWW::Mechanize for reading the form on an existing page and submitting values to it.
Nevertheless, I am realizing that, anyway, back in the day I had to inspect the forms from the HTML source code, since I had to discover that the form I was interested was the first one in the page, and that the parameters were those shown in the snippet.
So it is still more convenient, but not so much as I remembered.
The line between
Mojo::UserAgentandWWW::Mechanizegets blurry withTest::Mojo.Test::Mojocould very well have asubmit_form_okmethod, even if we considerMojo::UserAgenttoo low level.Ah yeah. There's even a role for
Test::Mojothat does have such method:Test::Mojo::Role::SubmitFormI also will watch this. Thanks for the reference!