6

我正在使用 WWW::Mechanize 在每隔几秒运行一次的循环中读取特定网页。有时,“GET”超时并且脚本停止运行。如何从这样的超时中恢复,以便它继续循环并在下一次尝试“GET”?

4

4 回答 4

4

使用eval

eval {
    my $resp = $mech->get($url);
    $resp->is_success or die $resp->status_line;
    # your code
};

if ($@) {
    print "Recovered from a GET error\n";    
}

eval块将在获取页面时捕获任何错误。

于 2010-09-22T06:02:56.327 回答
1

一种选择是实现一种方法来处理超时错误并在构造时将其作为onerror处理程序挂钩到 mech 对象中。请参阅文档中的构造函数和启动

您甚至可以通过设置 null 错误处理程序来忽略错误,例如:

my $mech = WWW::Mechanize->new( onerror => undef );

但我不建议这样做 - 你以后会遇到奇怪的问题。

于 2010-09-22T05:42:34.873 回答
0

此解决方案将继续尝试加载页面,直到它工作。

do {
    eval {
        $mech->get($url);
    };
} while ($@ ne '');
于 2013-12-12T18:18:18.153 回答
0

要获得更完整的解决方案,您可以使用 Try::Tiny::Retry 之类的模块。它允许您指定要运行的代码块,捕获任何错误,然后在可配置的时间内重试该代码块。语法很干净。

use WWW::Mechanize();
use Try::Tiny::Retry ':all';

my $mech = WWW::Mechanize->new();
retry {
    $mech->get("https://stackoverflow.com/");
}
on_retry {
    warn("Failed. Retrying. Error was: $_");
}
delay {
    # max of 100 tries, sleeping 5 seconds between each failure
    return if $_[0] >= 100;
    sleep(11 * 1000 * 1000);
}; #don't forget this semicolon

# dump all the links found on the page
print join "\n", map {$_->text } $mech->links;
于 2018-10-11T19:22:27.023 回答