gpt4 book ai didi

perl - 有效处理 lwp 超时

转载 作者:行者123 更新时间:2023-12-04 09:54:14 30 4
gpt4 key购买 nike

我正在使用 LWP 从网页下载内容,我想限制它等待页面的时间。这是在 lwp 中完成的,如下所示:

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->get($url);

这工作正常,除了每当超时达到其限制时,它就会死掉,我无法继续使用脚本!我真的很想正确处理这个超时,以便我可以记录 url 有超时,然后继续我的下一个。有谁知道如何做到这一点?谢谢!

最佳答案

LWP::Agentget()返回 HTTP::Response可用于检查错误的对象:

use LWP::Agent;
use HTTP::Status ();

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $response = $ua->get($url);

if ($response->is_error) {
printf "[%d] %s\n", $response->code, $response->message;

# record the timeout
if ($response->code == HTTP::Status::HTTP_REQUEST_TIMEOUT) {
...
}
}

顺便说一句,现在更好的做法是使用 Try::Tiny而不是 eval {...} .它给你 try {...} catch {...} .它解决了检查 if $@ 的一些问题(请参阅 Try::Tiny 文档中的背景部分)。

关于perl - 有效处理 lwp 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10989783/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com