gpt4 book ai didi

perl - 如何在不使用 Perl 和 LWP 获取页面的情况下获取最终 URL?

转载 作者:行者123 更新时间:2023-12-04 13:10:13 27 4
gpt4 key购买 nike

我正在做一些 web scraping使用 Perl 的 LWP。我需要处理一组 URL,其中一些可能会重定向(1 次或多次)。

如何使用 HEAD 方法获取解析所有重定向的最终 URL?

最佳答案

如果您使用 LWP::UserAgent 的全功能版本,那么返回的响应是 HTTP::Response 的一个实例它又作为一个属性 HTTP::Request .请注意,这不一定与您使用一组 URL 中的原始 URL 创建的 HTTP::Request 相同,如 HTTP::Response 文档中描述的在响应实例中检索请求实例的方法:

$r->request( $request )

This is used to get/set the request attribute. The request attribute is a reference to the the request that caused this response. It does not have to be the same request passed to the $ua->request() method, because there might have been redirects and authorization retries in between.


一旦你有了请求对象,你就可以使用 uri 方法来获取 URI。如果使用了重定向,则 URI 是遵循重定向链的结果。
这是一个经过测试和验证的 Perl 脚本,它为您提供了所需的框架:
#!/usr/bin/perl

use strict;
use warnings;

use LWP::UserAgent;

my $ua; # Instance of LWP::UserAgent
my $req; # Instance of (original) request
my $res; # Instance of HTTP::Response returned via request method

$ua = LWP::UserAgent->new;
$ua->agent("$0/0.1 " . $ua->agent);

$req = HTTP::Request->new(HEAD => 'http://www.ecu.edu/wllc');
$req->header('Accept' => 'text/html');

$res = $ua->request($req);

if ($res->is_success) {
# Using double method invocation, prob. want to do testing of
# whether res is defined.
# This is inline version of
# my $finalrequest = $res->request();
# print "Final URL = " . $finalrequest->url() . "\n";
print "Final URI = " . $res->request()->uri() . "\n";
} else {
print "Error: " . $res->status_line . "\n";
}

关于perl - 如何在不使用 Perl 和 LWP 获取页面的情况下获取最终 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470053/

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