HTML::TreeBuilder 超时

问题描述 投票:0回答:1

我想知道是否有一些优雅的方法来实现 timeout

HTML::TreeBuilder


我目前的实现如下:

use constant WEB_AGENT   => 'Mozilla/5.0';
use constant WEB_TIMEOUT =>  10;
use constant url         => 'https://...';

my $tree;

eval {
  local $SIG{ALRM} = sub { die "Timeout\n"; };
  alarm(WEB_TIMEOUT);
  $tree = do {
    local $SIG{__WARN__} = sub { };
    local *LWP::UserAgent::_agent   = sub { WEB_AGENT   };
  # local *LWP::UserAgent::_timeout = sub { WEB_TIMEOUT };
    HTML::TreeBuilder->new_from_url(url);
  };
  alarm(0);
};
# check $@

是否可以避免使用

alarm

perl
1个回答
0
投票

Mojolicious 彻底改变了这一点,我认为这使得这变得更加容易。我不需要把各种东西拼凑在一起,也不需要努力去颠覆它们的内部。以下是 Mojo 如何做到这一点的概述:

my $ua = Mojo::UserAgent->new(...);
$ua->transactor->name( $user_agent_string );
$ua->request_timeout(5);

my $tx = $ua->get($url);

my $dom = $tx->res->dom;  # play with the HTML through its DOM representation

我在 https://leanpub.com/mojo_web_clients/中展示了更多示例。

如果您想仍然使用 HTML::TreeBuilder,我建议您创建一个最小的子类,添加一个方法来返回内部 LWP 对象,以便您可以以通常的方式影响它。请注意,您已经可以通过 LWP::UserAgent 的公共方法来设置您想要的东西了。

© www.soinside.com 2019 - 2024. All rights reserved.