r/perl•
atsider

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

510
zoffix•

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?

7
atsiderOP•

Well, I recently discovered Mojo::DOM, and that I could use it to replace my clunky use of HTML::Parser, and I thought that I could go using just the Mojo framework 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!

4
daxim•

Mojo::DOM

Try Mechanize + Web::Query(::LibXML).

WQ is the best declarative HTML parser.

3
atsiderOP•

Nice, thanks!

1
Grinnz•

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.

2
atsiderOP•

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.

1
kraih•

The line between Mojo::UserAgent and WWW::Mechanize gets blurry with Test::Mojo. Test::Mojo could very well have a submit_form_ok method, even if we consider Mojo::UserAgent too low level.

1
zoffix•

Ah yeah. There's even a role for Test::Mojo that does have such method: Test::Mojo::Role::SubmitForm

2
atsiderOP•

I also will watch this. Thanks for the reference!

1
kraih•

This is on the todo list for Mojolicious, and i've made a few attempts to add it already. But so far it always got blocked by obvious bugs, or lack of enthusiasm from the community. Last one was a few weeks ago. https://github.com/kraih/mojo/commit/861193d93e4d83b624a91c87987254f5aeda3a6e

3