问题
I'm using WWW::Mechanize::Firefox and am trying to use the synchronize method like so:
$mech->get('http://example.com/wp-login.php');
$mech->submit_form( with_fields => {log => 'admin', pwd => 'password'});
$self->synchronize( 'DOMContentLoaded', sub {print Dumper($self->title()); });
exit;
The title of the newly loaded page prints but then the script just hangs. It never exits. What am I missing?
回答1:
The subroutine that you pass to synchronize is meant to do something that kicks off an update to the browser page. synchronize calls it and then waits for the event you have specified before it returns
Clearly your print statement won't change the web page at all, so no events will fire and your code will be suspended indefinitely
I suggest you put the call to submit_form in the subroutine you pass to synchronize. That at least stands a chance of causing DOMContentLoaded to fire
It would look like this
$mech->get('http://example.com/wp-login.php');
$mech->synchronize('DOMContentLoaded', sub {
$mech->submit_form( with_fields => { log => 'admin', pwd => 'password' });
});
print Dumper $self->title;
回答2:
Short Two solutions below -- Don't specify the event to wait for (so that its default list is used), or use click method which does wait on its own, instead of submit_form.
I see the same problem with form_submit, and with the synchronize method. Either the next call still gets the page being submitted, or the script hangs with synchronize (used, correctly, as in Borodin's answer). I test with a site which does a bit of work as a form is submitted.
Wrapping calls in synchronize is borne with some subtleties. What events are fired or not is not clear and can also be affected (earlier in the code). I found that the code works when no events are specified in the call, and the default list of events() is thus checked for.
mech->synchronize( sub {
$mech->submit_form( with_fields => { log => 'admin', pwd => 'password' } );
});
$mech->save_content('after_submit.html');
The following call gets the correct page.
The documentation never mentions waiting with form methods, so some synchronization is needed. However, the click method does wait, by default (one can change that with synchronize option).
So I found this to solve the problem as well: Fill the form and click it.
# Get the page with the form
$mech->fields( log => 'admin', pwd => 'password' );
$mech->click( name => 'Login' ); # whatever the name is
$mech->save_content('after_submit.html');
The next call after click gets the actual next page.
In case the form has no name on <input>, for example, this works as well
$mech->click_button(input => 'submit');
来源:https://stackoverflow.com/questions/36243320/how-to-use-synchronize-method-with-wwwmechanizefirefox