如何阅读本身可能被重定向到另一个网址的网页内容?
问题描述:
我使用这个代码来读取网页内容:如何阅读本身可能被重定向到另一个网址的网页内容?
my $ua = new LWP::UserAgent;
my $response= $ua->post($url);
if ($response->is_success){
my $content = $response->content;
...
但如果$ URL指向移动页面,然后$响应 - > is_success是返回false。现在如何轻松获取重定向页面的内容?
答
你需要追逐重定向本身。
if ($response->is_redirect()) {
$url = $response->header('Location');
# goto try_again
}
您可能想把它放在while循环中,并使用“next”而不是“goto”。您可能还需要记录它,限制重定向你愿意追逐,
[更新]
OK我才注意到还有一个更简单的方法来做到这一点的号码等。从LWP :: UserAgent的手册页:
$ua->requests_redirectable $ua->requests_redirectable(\@requests) This reads or sets the object's list of request names that "$ua->redirect_ok(...)" will allow redirection for. By default, this is "['GET', 'HEAD']", as per RFC 2616. To change to include 'POST', consider: push @{ $ua->requests_redirectable }, 'POST';
所以是的,也许只是这样做。 :-)
看来GET请求会自动在内部重定向。所以我这样做:我的$ agent = LWP :: UserAgent-> new(env_proxy => 1,keep_alive => 1,timeout => 30,agent =>“Mozilla/4.76 [en](Win98; U) “); my $ header = HTTP :: Request-> new(GET => $ link); my $ request = HTTP :: Request-> new('GET',$ link,$ header); my $ response = $ agent-> request($ request) – AgA 2011-05-29 06:40:29
是的,但您的问题使用'POST',您需要手动配置(或处理)。无论如何,很高兴你的工作。 – Nemo 2011-05-29 16:25:42
我的错误是,我只需要访问网页(GET)。那么这种常见的方式适用于GET和POST。 – AgA 2011-05-31 07:58:18