【问题标题】:How can I recover from a timeout with Perl's WWW::Mechanize?如何使用 Perl 的 WWW::Mechanize 从超时中恢复?
【发布时间】:2011-04-15 13:16:30
【问题描述】:

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

【问题讨论】:

    标签: perl www-mechanize


    【解决方案1】:

    要获得更完整的解决方案,您可以使用 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;
    

    【讨论】:

      【解决方案2】:

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

      do {
          eval {
              $mech->get($url);
          };
      } while ($@ ne '');
      

      【讨论】:

        【解决方案3】:

        使用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 块将在获取页面时捕获任何错误。

        【讨论】:

          【解决方案4】:

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

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

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

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

          【讨论】:

            猜你喜欢
            • 2014-04-14
            • 2016-04-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-14
            • 2011-10-25
            • 1970-01-01
            相关资源
            最近更新 更多