[英]How can I recover from a timeout with Perl's WWW::Mechanize?
我正在使用WWW :: Mechanize來讀取每隔幾秒運行一次的循環中的特定網頁。 偶爾,'GET'超時並且腳本停止運行。 如何從一個這樣的超時恢復,以便它繼續循環並在下一次嘗試'GET'?
使用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
塊將捕獲任何錯誤。
一種選擇是實現一種方法來處理超時錯誤,並在構造時將其作為onerror
處理程序掛鈎到mech對象中。 請參閱文檔中的構造函數和啟動 。
您甚至可以通過設置空錯誤處理程序來忽略錯誤,例如:
my $mech = WWW::Mechanize->new( onerror => undef );
但我不建議 - 你以后會遇到奇怪的問題。
此解決方案將繼續嘗試加載頁面,直到它工作。
do {
eval {
$mech->get($url);
};
} while ($@ ne '');
要獲得更完整的解決方案,您可以使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.