How do I fetch just the beginning of a Web page with LWP?

好久不见. 提交于 2019-12-01 11:16:11
use 5.010;
use strictures;
use LWP::UserAgent qw();

my $content;
LWP::UserAgent->new->get(
    $url,
    ':content_cb' => sub {
        my ($chunk, $res) = @_;
        state $length = $res->header('Content-Length');
        $content .= $chunk;
        die if length($content) / $length > 0.5;
    },
);

If the web site in question suppplies the Content-Length header you can just ask how much data is going to be sent and request only half of it.

This code demonstrates.

use strict;
use warnings;

use LWP;

my $ua = LWP::UserAgent->new;
my $url = 'http://website.test';

my $resp = $ua->head($url);
my $half = $resp->header('Content-Length') / 2;

$resp = $ua->get($url, Range => "bytes=1-$half");
my $content = $resp->content;

If the web application needs a long time to render the page you will usually have no possibility to accellerate the process by fetching 'half' of the page.

The page will be delivered after all the database queries and the actual rendering is done. And those are likely the reason for the long delays.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!